Angular2 Forms Tutorial: Creating Custom Validators

Every now and then developers come across situations where existing validators are not suitable for their needs, if you are facing this situation your best option is to create a custom validatior, to illustrate how you can do that in angular2 I’m going to create a simple custom validator that will verify if the field value starts with a given string, it’ll be something like this:

<input type="text" startWith="ABC" ...>

In this example the attribute startWith is my validator, for this input to be valid it must contain a value that starts with ABC.

Now let’s see how it works, a custom validator is nothing more than a attribute directive that implements the Validator class, before we proceed to the details let’s take a look at the code:

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
 
@Directive({ 
  selector: '[startWith]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] 
})
export class CustomValidatorDirective implements Validator{
  @Input('startWith') expr: string;
 
  validate(control: AbstractControl) {
    if(control.value && !control.value.startsWith(this.expr)){
        return {'startWith': control.value};
    }
    return null;
  }
}

Every validator has a validate() method, angular2 will call it every time the application needs to validate the field, note that it receives an AbstractControl as a parameter, which is the form control itself, this parameter will give us access to all of the field attributes, including the value (the only one we’re going to use in this tutorial). Also note that I’ve declared an @Input, this is how I’m getting the value "ABC" passed to the directive in the example above.

Now that we have the field value and the input we can implement the validate method and check if the field value contains the expression. If the field is valid the function returns null, otherwise it returns the validation error object.

Lastly, before you can use the validator, you have to register it in the app.modules.ts:

...
import { CustomValidatorDirective } from './customValidator.directive';
 
@NgModule({
  declarations: [ ... ,CustomValidatorDirective],
  ...
})
export class AppModule { }

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>