zoukankan      html  css  js  c++  java
  • [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
        );
      }
  • 相关阅读:
    公有云数据库服务的申请与使用
    linux集群
    shell基础知识
    LNMP环境配置
    LAMP环境搭建与配置
    12月17日linux学习
    12月16日linux学习(文档的压缩与打包)
    12月13、14号linux学习
    12月12日linux学习
    目录结构
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7402283.html
Copyright © 2011-2022 走看看