Sameer K
Sameer K

Reputation: 799

Angular2 : how to set Validators.required as common validation for 2 fields

I am using Angular2 ForumBulder to create form and to add validations. Below the sample code from component

this.OtpForm = this._fb.group({
    otpInput: this._fb.group({
      otpInput1: ['', Validators.required],
      otpInput2: ['', Validators.required],
      otpInput3: ['', Validators.required],
    }, { validator: this.numericValidator })
});

Now this works fine. But question is how to Validators.required as common to all the field just like custom validator numericValidator?

Upvotes: 0

Views: 413

Answers (1)

Tiep Phan
Tiep Phan

Reputation: 12596

you could create one more custom validator for otpInput group, for example

validateAllRequired(g: FormGroup) {
    let ctrls = g.controls;
    let keys = Object.keys(ctrls);
    let valid = true;
    keys.forEach((key) => {
      let ctrl = ctrls[key];
      if (ctrl.value.trim() == '') {
        valid = false;
      }
    });
    return valid ? null : {
      validateAllRequired: {
        valid: valid
      }
    };
}

and add to this:

otpInput: this._fb.group({
  otpInput1: [''],
  otpInput2: [''],
  otpInput3: [''],
}, { validator: Validators.compose([this.numericValidator, this.validateAllRequired]) })

combine validators using Validators.compose()

Validators.compose([...])

for async validators use

Validators.composeAsync([...])

Upvotes: 3

Related Questions