SelectListCustomValidator Directive

Select List Custom Validator Directive

Configurable Select List Custom Validator Directive

Cross Field Validation – Compare Validation Directive

Trigger Validation Manually

Angular form group validation



<div ngModelGroup="passwordGroup" #passwordGroup="ngModelGroup"
      appConfirmEqualValidator [class.has-error]="passwordGroup.errors?.notEqual
      && !confirmPassword.errors?.required">

  <div class="form-group"
        [class.has-error]="password.touched && password.invalid">
    <label for="password" class="control-label">Password</label>
    <input name="password" required type="text" class="form-control"
            [(ngModel)]="employee.password" #password="ngModel">
    <span class="help-block"
          *ngIf="password.touched && password.errors?.required">
      Password is required
    </span>
  </div>

  <div class="form-group"
        [class.has-error]="confirmPassword.touched && confirmPassword.invalid">
    <label for="confirmPassword" class="control-label">Confirm Password</label>
    <input name="confirmPassword" required type="text" class="form-control"
            [(ngModel)]="employee.confirmPassword" #confirmPassword="ngModel">
    <span class="help-block"
          *ngIf="confirmPassword.touched && confirmPassword.errors?.required">
      Confirm Password is required
    </span>
    <span class="help-block" *ngIf="confirmPassword.touched &&
          passwordGroup.errors?.notEqual && !confirmPassword.errors?.required">
      Password and Confirm Password does not match
    </span>
  </div>

</div>

Custom Validator Code :


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

@Directive({
    selector: '[appConfirmEqualValidator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: ConfirmEqualValidatorDirective,
        multi: true
    }]
})
export class ConfirmEqualValidatorDirective implements Validator {
    validate(passwordGroup: AbstractControl): { [key: string]: any } | null {
        const passwordField = passwordGroup.get('password');
        const confirmPasswordField = passwordGroup.get('confirmPassword');
        if (passwordField && confirmPasswordField &&
            passwordField.value !== confirmPasswordField.value) {
            return { 'notEqual': true };
        }

        return null;
    }
}

NgModelGroup Directive

  • Use to create a sub-group within a form
  • Useful to validate a sub-group of elements on the form
  • Useful to group properties of the form model in to a nested object
  • The name of the ngModelGroup will become the key for the nested object in the form model
  • The ngModelGroup directive can only be used as a child of NgForm directive

Leave a Reply

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