Home > database >  multiple regex validation with api response in angular for password field
multiple regex validation with api response in angular for password field

Time:12-20

I have an API response with validator conditions (true/false).

If the response is true, then we need to set that validator in the Password field. Similarly, we need to do it for other true responses from API.

Then we need to write and display an inline error message if validators are not met.

I have tested it like this:

  1. The API response is an object

In the TS file, So now I have written conditions based on API response for eg: mustAlpha:true

//variable regex
mustAlpha= /^(?=.*[a-zA-Z])/;

ngOnInit():void{
this.buildForm();
this.passwordAPI();
}

//In class

buildForm(){
password:['', [Validators.required]]
}


passwordAPI(){
// API call goes here

if(response){

if(response.mustAlpha){
this.formName.get('password').setValidators([Validators.pattern(this.mustAlpha])
}}
}

In html file under password input box, I have wrriten this

<div *ngIf="(formName.get('password')?.touched && formName.get('password')?.invalid)">
Password does not minimum requirements

<div *ngIf="formName.get('password')?.errors?.['required']> Please enter password
</div>

</div>

However, I am not able see the validator getting applied in password input box. Can you please suggest?

CodePudding user response:

Angular provides a way to add asynchronous validators to a form - the validation will automatically wait until your API responds

You need to create a custom async validator that calls the API. There's a good example in the Angular docs:

CodePudding user response:

Right after setValidators, try

this.formName.get('password').updateValueAndValidity();
  • Related