• [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
        );
      }
  • 相关阅读:
    动态规划_leetcode70
    动态规划_leetcode64
    动态规划_leetcode63
    PHP处理base64编码字符串
    PHP解决h5页面跨域
    PHP对象转数组
    jQuery 正则
    mysql重置密码
    yii框架学习(获取插入后的id)
    nginx 之 root和alias
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7402283.html
Copyright © 2020-2023  润新知