[Angular] Custom directive Form validator

Create a directive to check no special characters allowed:

import {Directive, forwardRef} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, Validator} from '@angular/forms';
@Directive({
  selector: `[formControl][no-special-chars], 
             [formControlName][no-special-chars], 
             [ngModel][no-special-chars]`,
  providers: [
    {
      multi: true,
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => NoSpecialCharsValidator)
    }
  ]
})

export class NoSpecialCharsValidator implements Validator {
  validate(c: AbstractControl): { [key: string]: any; } {
    const res = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(c.value);
    return res ? {special: true}: null;
  }
}

 

        <div class="meal-form__name">
          <label>
            <h3>Meal name</h3>
            <input type="text"
                   no-special-chars
                   formControlName="name"
                   placeholder="e.g. English Breakfast">
            <div class="error" *ngIf="noSpecials">
              Cannot contain special characters
            </div>
          </label>
        </div>
  get noSpecial() {
    return (
      this.form.get('name').hasError('special') &&
        this.form.get('name').touched
    );
  }

 

posted @ 2017-08-21 01:53  Zhentiw  阅读(327)  评论(0编辑  收藏  举报