Gold100
Gold100

Reputation: 124

How to make multiple validation on field in angular 2?

I am building a model driven form in angular 2 and i want a specific field to have a range validation between 1-1000 and can also have values of 2000 and 2001,

I tried to put it in compose:

this.configForm.controls["field"].setValidators(Validators.compose([Validators.required,CustomValidators.equal(2000),CustomValidators.equal(2001), CustomValidators.range([1,1000])]));

But it didn't work..

How to do it?

Thanks.

Upvotes: 0

Views: 727

Answers (2)

Michael Kang
Michael Kang

Reputation: 52847

If you are using FormBuilder, then consider implementing a group validator that validates a group of controls rather than individual ones:

How to do simple cross field validation in Angular 2 form to pass validation if one of the control in group has value?

The second argument to FormBuilder's group method allows you to specify a group validator:

 this.fb.group({
     field1: [''],
     field2: [''],
     }, 
     {
         validator: (c:FormGroup) => {
              return {'whateveryouwant': true};
         }
     }
 );

If you need to clear the fields validation flags:

let field1 = c.get('field1');
field1.setErrors(null);

Upvotes: 1

Suraj Rao
Suraj Rao

Reputation: 29625

According to FormControl API, there is no setValidators() function.

You may have to add new control:

this.configForm.controls["field"] = new FormControl('',Validators.compose([
      Validators.required,CustomValidators.equal(2000),
      CustomValidators.equal(2001), 
      CustomValidators.range([1,1000])]
      ));

Upvotes: 0

Related Questions