【问题标题】:resuable validator for multiple cases多个案例的可重用验证器
【发布时间】:2017-02-20 17:55:37
【问题描述】:

我做了一个日期验证器。它验证现有日期。我需要具有其他限制的多个日期验证器,例如:不允许用户输入未来日期的最大日期验证器或只接受过去日期的日期验证器。这是我当前的验证器。

    export function dateValidator(group) {

  const {day, month, year} = group.value;
  const fullDate = `${day}/${month}/${year}`;
  const dobPattern = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/;
  const isStringValid = dobPattern.test(fullDate);

  let isValid = false;

  if (isStringValid) {
    const intDay = Number(day);
    const intMonth = Number(month);
    const intYear = Number(year);
    const jsMonth = intMonth - 1;
    const date = new Date(intYear, jsMonth, intDay);
    isValid = (date.getFullYear() === intYear && date.getMonth() === jsMonth && date.getDate() === intDay ;
  }

  return isValid ? null : { invalid: 'Invalid date' };
};

如何限制用户输入未来的日期。 我将此代码与以下行一起使用:

    isValid = (date.getFullYear() === intYear && date.getMonth() === jsMonth && date.getDate() === intDay ;

但我想知道是否有一种更简单的方法,而不必一遍又一遍地复制和粘贴这段代码来对其进行小的限制。

【问题讨论】:

    标签: validation angular custom-validators reactive-forms


    【解决方案1】:

    您的dateValidator() 函数应该是一个函数工厂(即返回函数的函数)而不是直接返回错误的函数:

    export function dateValidator(maxDate: string): ValidatorFn {
      // Return a validator function.
      return (group: FormGroup): {[key: string]: any} => {
        // Re-use your existing validation code here and return the error if any.
        // Optionally, use the `maxDate` param to customize the validation:
        // entered dates should not go beyond `maxDate`.
      };
    }
    

    如您所见,您可以通过将参数传递给函数工厂来自定义验证器函数。在我的示例中,我使用了maxDate 参数来指示验证器应该允许的最远日期。

    在您的表单模型中,通过调用具有适当值的工厂来使用此验证器,例如:

    this.myForm = fb.group({
      'date': ['', [Validators.required(), dateValidator('02/20/2017')]]
    });
    

    您可以在文档中看到另一个用于验证器的函数工厂示例:https://angular.io/docs/ts/latest/cookbook/form-validation.html#custom-validation

    【讨论】:

    • 这是否意味着我必须复制并粘贴多个验证器的代码?我是新手。
    • 没有。如果您正确组织代码,则不需要复制/粘贴。只需像我解释的那样创建一个 dateValidator 函数工厂,其中包含自定义其工作方式所需的所有参数(如我的示例中的 maxDate)。然后在需要它的所有字段中使用该验证器,每次使用验证器时可能都必须传递不同的参数。
    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多