Here, we discuss the approach of how to compare the password with the RxwebValidators.
Why RxwebValidator?
Comparing the password is possible with the standard approach as well. Because angular provides a feature to manage the cross-field validation. But I see some design issue with the standard approach of Angular. If I refer to the angular doc on cross-field validation. The Angular doc suggests that the custom validator I have to put on FormGroup level for comparing two fields or some other actions. This approach is less appropriate for large/complex forms. Because that custom validator makes a call every FormControl value changes, blur, etc events.
Let's see the below screenshot, The custom validator is calling non-validation field as well, The code I have copied from Angular Doc.
As per the above screenshot, I am entering the value in the 'power' FormControl and this FormControl isn't have relation with validation in the Form. But still, the custom validator is calling while entering the value in this FormControl.
Now, we talk about RxwebValidator to overcome this problem.
First of all, we have to install the package @rxweb/reactive-form-validators
npm install @rxweb/reactive-form-validators
Once it's installed, we have to register the 'RxReactiveFormsModule' in the root module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RxReactiveFormsModule } from "@rxweb/reactive-form-validators"
@NgModule({
imports: [ BrowserModule, FormsModule,ReactiveFormsModule,RxReactiveFormsModule ],
declarations: [ AppComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Now let's create two FormControls inside the FormGroup and use the compare validator of RxwebValidator. The two FormControls are 'password' and 'confirmPassword'.
The functional requirement is if I change the value any one of the FormControl, the validation should fire.
We apply the compare validator on 'confirmPassword' FormControl.
this.userForm = this.formBuilder.group({
'password': '',
'confirmPassword':['',RxwebValidators.compare({fieldName:'password'})]
});
As we have provided the fieldName of 'password' FormControl in the compare validator to compare the value with the 'password' FormControl.
See the action below:
You can refer to the stackblitz example of compare password.
All done!.
If you have any question/suggestion, Please share your comments below.
Top comments (0)