Custom Validators for Angular 4
On a recent Angular 4 project I had the need to use some custom form validations. Out of the box, Angular 4 contains validators for required, email, pattern, and min/max length, and it is possible to write your own validators as well. In particular, the custom validation I needed to do was verify that two fields were equal. For example, a form where the user enters a phone number, and then confirms the phone number in a second form field. The custom validation would verify that the two text inputs had the same value.
Before writing my own validator for this, I did a quick search for something that already existed in the custom-validation space for Angular 4. What I found was an npm package called ng2-validation. (npm site here).
ng-validation contains 25 different custom validators, and it works with both template and model driven forms – so whichever one you are using all of the validators will work. It also happens to contain a validator called equalTo which fits my requirement for the phone number confirmation example.
To get started with ng2-validation, you need to import the CustomFormsModule in your app.module:
import { CustomFormsModule } from 'ng2-validation';
and then import the module
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpModule, BrowserAnimationsModule, AppRoutingModule, SharedModule, CustomFormsModule ]
Using Reactive Forms, the setup in the component would look like this:
const phone = new FormControl('', [Validators.required]); this.form = this.fb.group({ phone: phone, confirmPhone: ['', [CustomValidators.equalTo(phone)]] });
So unless confirmPhone has the same value as phone, the confirmPhone field (and subsequently, the form) will be invalid. One thing to note: normally I do not create a separate object for each form field – I just define the initial value and validators with the fb.group setup (e.g. confirmPhone). However, from what I have seen equalTo requires that an actual FormControl instance be created and passed as the parameter to equalTo (e.g. phone = new FormControl(…).
I like the API for equalTo, plus it saved me the work of creating a custom validator for what amounts to a very common scenario.
Other custom validators that are part of the package include:
- rangeLength
- min
- gt
- gte
- max
- lt
- lte
- range
- digits
- number
- url
- date
- minDate
- maxDate
- dateISO
- creditCard
- json
- base64
- phone
- uuid
- equal
- notEqual
- equalTo
- notEqualTo