在Angular 2反应性表单的表单字段中有条件地实现验证 [英] Conditionally implement validation in form fields of an Angular 2 reactive form

查看:76
本文介绍了在Angular 2反应性表单的表单字段中有条件地实现验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有条件地以Angular 2反应形式实现验证吗?我有这个带有3个formControl字段的反应形式,一个是选择,另外两个是名字和姓氏的输入文本.我想基于对第一个字段"validateBy"的选择,有条件地实现对姓氏和名字的验证.如果用户选择"byFirstName",则只应验证firstName.如果用户选择"byLastName",则仅对lastName进行验证.如果用户选择'byBoth',则firstName和lastName均应被验证.我为此创造了一个小矮人.只有byBoth的验证才有效.

Can I conditionally implement validation in Angular 2 reactive form. I have this reactive form with 3 formControl fields one is a selection and the other two are input text for first name and last name. I want to conditionally implements validation for firstname and lastname based on the selection of the first field which is 'validateBy'. If the user selects 'byFirstName' only firstName should be validated. If the user selects 'byLastName' only lastName should be validated. If the user selects 'byBoth' both firstName and lastName should be validated. I created a plunker for this. Only validation byBoth works.

ngOnInit() {
this.myForm = this._fb.group({
  validateBy: ['byFirstName'],
  firstName:  ['', isFirstNameValid(() => (this.validateBy === 'byFirstName' || this.validateBy === 'byBoth'),
                     Validators.required)],
  lastName: ['', isLastNameValid(() => (this.validateBy === 'byLastName' || this.validateBy === 'byBoth'),
                     Validators.required)],
}); 

https://plnkr.co/edit/X0zOGf?p=preview

推荐答案

问题是您的代码仅在创建FormGroup时对表达式进行一次评估.您需要通过创建自定义验证器使其动态化,该验证器将在每次调用表达式时对其进行求值:

The problem is that your code evaluates the expression just once - when the FormGroup is created. You need to make it dynamic by creating your custom validator that will evaluate the expression every time it gets called:

this.personForm= this.fb.group({
  firstName: ['', Validators.required];
  lastName:  [
    '', 
    conditionalValidator(
      (() => this.isValidationForLastName === true),
      Validators.required
    )
  ]
});

function conditionalValidator(condition: (() => boolean), validator: ValidatorFn): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    if (! condition()) {
      return null;
    }
    return validator(control);
  }
}

这篇关于在Angular 2反应性表单的表单字段中有条件地实现验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆