Angular 2: Apply Validator.required validation on some condition

折月煮酒 提交于 2019-11-29 02:27:58

You can add or remove a validator based on the the value of another control on the form:

    testForm: FormGroup;

    constructor(private formBuilder: FormBuilder) {
      this.testForm = this.formBuilder.group({
        condition: [''],
        description: ['']
      });

      this.testForm.controls['condition'].valueChanges.subscribe(result => {
        if (result) {
          this.testForm.controls['description'].setValidators(Validators.required);
          this.testForm.controls['description'].updateValueAndValidity();
        } else {
          this.testForm.controls['description'].setValidators(null);
          this.testForm.controls['description'].updateValueAndValidity();
        }
      });
    }

If descReq needs to be evaluated at run-time (rather than when its initialized), then perhaps you should create a custom validator:

import { ValidatorFn, AbstractControl } from '@angular/forms';
interface ValidationResult {
    [key:string]:boolean;
}
function customValidator(condition: { required:boolean }) {
     return (control: AbstractControl) :ValidationResult  => {
         return condition.required && 
             (control.value == undefined || 
              control.value == null || 
              control.value.trim() =='') ? 
              {
                 'required': true
              }: null;

       }

}

Use like this:

description:  ['', customValidator(this.reqd)]

where reqd has been initialized earlier, and maybe even data-bound:

reqd = { required: false };

You should set the validator on the field imperatively vs declaratively.

Declaratively (your current code):

const description = new FormControl('', Validators.required);

Imperatively:

const description = new FormControl('');
if (someCondition) {
  description.setValidators(Validators.required);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!