【问题标题】:Custom Angular Validators- Passing an Argument自定义 Angular 验证器 - 传递参数
【发布时间】:2017-01-06 10:06:09
【问题描述】:

我已关注Josh Moroney's tutorial 创建自定义验证器。我搞定了,可以打电话了

newForm.ts

new FormControl(question || '', 
    Validators.compose([AgeValidator.ageIsValid])
);

AgeValidator.ts

interface ValidationResult {
  [key: string]: any;
}

export class AgeValidator {
  static ageIsValid(control: AbstractControl): ValidationResult {
    console.log('this is control', control);
    console.log('this is control.value', control.value);

    if (isNaN(control.value)) {
      return {
        notValid: true,
        message: 'this is not a number'
      };
    }
    if (control.value % 1 !== 0) {
      return {
        notValid: true,
        message: 'cant be zero'
      };
    }

    if (control.value < 18) {
      return {
        notValid: true,
        message: 'cant be less than 18'
      };
    }
    if (control.value > 120) {
      return {
        notValid: true,
        message: 'Must be less than 120'
      };
    } else {
      return null;
    }
  }
}

是否可以在.ageIsValid 方法中添加一个参数,以便我可以指定有效的年龄?例如,

new FormControl(question || '', 
    Validators.compose([AgeValidator.ageIsValid(18)])
);

我尝试过的:

1) 摆脱 static 并像使用其他任何方法一样使用 .ageIsValid。结果:TS 错误

2) 像上面那样传递一个参数。结果:错误

还有什么我可以尝试的吗?

【问题讨论】:

    标签: angular validation ionic-framework


    【解决方案1】:

    您可以使用带有实例方法的类(而不是静态方法)

    class AgeValidator {
      constructor(private someParam) {}
      ageIsValid(control: AbstractControl): ValidationResult {
        // use someParam here
      }
    }
    
    var ageValidator = new AgeValidator('foo')
    new FormControl(question || '', 
        Validators.compose([ageIsValid.ageIsValid.bind(ageValidator)])
    );
    

    或返回函数的函数

    static ageIsValid (someParam) {
      return (control: AbstractControl): ValidationResult => {
        // use someParam here
      }
    }
    
    new FormControl(question || '', 
        Validators.compose([ageIsValid('foo')])
    );
    

    【讨论】:

    • 优秀!我选择了第二个选项。第一个给了我一堆错误(Can't find control)。第二种选择现在似乎对我有用。我唯一的问题是,为什么在调用方法时不需要包含AgeValidator?感谢您的所有帮助!
    • 我也更喜欢第二个。我更新了第一个。如果您在ageIsValid() 中使用this,这样它也应该可以工作。我不知道究竟是什么导致了你的错误。
    • 我需要做的另一件事是在您的第二个答案中的ValidationResult 之后添加一个火箭。 ValidationResult =&gt; { // use someParam here } 否则 TS 给我一个错误。
    • 对,我从类方法中复制时忘记了这一点。对不起。
    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2020-01-26
    • 2016-08-13
    相关资源
    最近更新 更多