1
votes

Can anyone please share an example of how to create a custom validator for template driven forms in Angular 2.4?

3

3 Answers

0
votes

There is an article demonstrating creation of custom validation rule for both reactive and template forms. You can find it here - https://angular.io/guide/form-validation#custom-validation-directive

0
votes

You can create a directive for this and here is an example:

enter image description here

Then you can use it in your template like here:

<input myCustomValidation [(ngModel)]="MyValue" #myValue="ngModel">

You can also add additional fields to your validation like this:

validate(formGroup: FormGroup): ValidationErrors {
  const passwordControl = formGroup.controls["password"];
  const emailControl = formGroup.controls["login"];

  // for example check if email and password fields have value
  if (!passwordControl || !emailControl || !passwordControl.value || !emailControl.value) {
    return null;
  }

  // do validation here using passwordControl.value and emailControl.value

  return formGroup;
}
0
votes

Sharing a template driven form example for reference that helped me to understand ,hope it will help someone in future

Lets create a template as given below

<input id="name" name="name" class="form-control"
      required appValidator
      [(ngModel)]="hero.name" #name="ngModel" >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.appValidation">
    Name cannot be Bob.
  </div>

</div>

For the custom validation in this example have created a simple directive that implements the check ,and returns null if condition is true or returns a validation error object ,the directive code is given below

import { Directive } from '@angular/core';
import{NG_VALIDATORS,ValidationErrors,Validator,AbstractControl} from '@angular/forms'

@Directive({
  selector: '[appValidator]',
  providers:[{provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true}]
})
export class ValidatorDirective implements Validator {

  constructor() { }

  validate(control:AbstractControl):ValidationErrors|null{

    const val = control.value;
    if(val === "Bob"){
      return {appValidation:"Bob is not allowed"};
    }else{
      return null;
    }
    
  }

}