1

I have a field in my reactive angular form and I am trying to add validations to it. In my service class, I am able to use Validators.required which is by default provided by angular as follows

Countrycode: new FormControl('', [Validators.required, Validators.maxLength(12)])

But condition is, If country is Canada then this Validators.required should work else Validators.required is not needed. If country is other then Canada, only maxLength validation is needed as done above. How can I do that?

3
  • 1
    You need to check if the country is Canada and if so, set your validators accordingly, simple as that ;) If you are having issues, show us the actual code you are struggling with and what exactly is wrong with it. Commented Sep 26, 2019 at 17:12
  • that is my validation code. I am new to angular so don't know how to do it Commented Sep 26, 2019 at 17:17
  • well you need to set the validators conditionally. Google for example: "conditional validation angular" or search on Stackoverflow, there is similar questions. Asking on SO should show some attempt to solve the issue, it is not a free coding service. Please try something first and come back if you face issues :) Commented Sep 26, 2019 at 17:21

2 Answers 2

3

In addition to Irwing's answer you can subscribe to the FormControl change using this:

this.form.get('CountryCode').valueChanges.subscribe(val => {
    onChangeCountry(val);
});

However, instead of listening for changes, best practice would be to inject your own custom validation function as part of the control:

Countrycode: new FormControl('', [countryValidator, Validators.maxLength(12)])


export function countryValidator(control: AbstractControl) {
     if (otherValue == 'Canada' && !control.Value) {
        //validation fails
        return { invalid: true };
     }
     //validation passes
     return null;
  };
}

HTH

Sign up to request clarification or add additional context in comments.

2 Comments

what is this othervalue
@user4444 I just used it as an example, its likely not relevant to your case but you just need to apply whatever condition is applicable in that if statement to make this work.
1

You could update the Country Validators by selecting it, as the following code:

onChangeCountry(country) {    
   if (country == "Canada") {
       this.form.controls.country.setValidators([Validators.required,Validators.maxLength(12)]);
   }else {    
       this.form.controls.country.setValidators([Validators.maxLength(12)]);


         } 
  this.form.controls.country.updateValueAndValidity();
}

1 Comment

how to add validation message in this . If field is empty I want to display field is mandatory. If field is not empty but have more than 12 characters then want to display cannot have more than 12 characters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.