how to create custom validator function

Step 1 : Create the custom validator function 
function emailDomain(control: AbstractControl): { [key: string]: any } | null {
  const email: string = control.value;
  const domain = email.substring(email.lastIndexOf('@') + 1);
  if (email === '' || domain.toLowerCase() === 'gmail.com') {
    return null;
  } else {
    return { 'emailDomain'true };
  }
}

Step 2 : Attach the custom validator function to the control that we want to validate

email: ['', [Validators.required, emailDomain]]

Step 3 : Display the validation error message

<span *ngIf="employeeForm.get('email').errors.emailDomain">
  Email domian should be gmail.com
</span>

Comments

Popular posts from this blog

how to save images with angular nodejs

How to restrict your logged In page in angular (authentication guard)

How to notify about data update to other component.