Angular 2: Apply Validator.required validation under some condition

I have an angular 2 form in which I need to create the field required for some conditions, such as:

description:  ['', Validators.required]

This description field is required only for some type of condition, for example:

if(true){descReq = true};

How can I achieve this, please suggest. Thanks in advance!

+4
source share
3 answers

You can add or remove a validator based on the value of another control in 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();
        }
      });
    }
+2
source

If you descReqneed to evaluate at runtime (rather than initializing it), you might need to 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;

       }

}

:

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

reqd , , :

reqd = { required: false };
0

You must set the validator in the field imperatively against declarative.

Declaratively (your current code):

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

Strongly:

const description = new FormControl('');
if (someCondition) {
  description.setValidators(Validators.required);
}
0
source

Source: https://habr.com/ru/post/1669763/


All Articles