【问题标题】:Custom Directive to display inbuilt and custom error one at a time自定义指令一次显示一个内置和自定义错误
【发布时间】:2019-06-18 23:36:45
【问题描述】:

我需要比较输入文本是否首先与内置错误(如 required、minlength、maxlength、pattern)匹配,然后检查输入是否也满足我的自定义条件。

为了应用自定义条件,我使用了自定义验证器指令。当我使用此指令时,它一次显示多个错误消息。我厌倦了所有组合,但仍然无法一次只收到一条错误消息。

所以我需要编写一个可以显示的通用指令:
1)所有内置错误,然后显示我们的自定义错误。
2) 一次只显示一个错误
3) 应优先考虑内置错误,如 required、pattern 等,然后检查我们的自定义条件。

HTML 代码

<form name="checkForm" #checkForm="ngForm">
    <label>Check Code :<br>
        <input type="text" name="checkFiled" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"
            [(ngModel)]="checkNgFiled" #checkFiled="ngModel" autocomplete="off"
            [MatchInput]="checkVar">
    </label><br>
        <div *ngIf="(checkFiled.touched || checkFiled.dirty) && checkFiled.invalid"
            class="ErrCls">
            <span *ngIf="checkFiled.errors.required">Input is Empty.</span>
            <span *ngIf="checkFiled.errors.pattern">Code is weak</span>
            <span *ngIf="checkFiled.errors.unMatchError">Input do not match</span><br>
        </div>

    <button [disabled]="!checkForm.valid">Check</button>
</form>

TS 代码

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

@Directive({
    selector: '[MatchInput]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: MatchInputCls, multi: true }
      ]
})
export class MatchInputCls implements Validator
{
    @Input() MatchInput: string;

    validate(inputControl: AbstractControl): ValidationErrors | null
    {

// Need a proper condition to first check for inbuilt errors, It its present my code should return null, 

        if(!inputControl.errors || (inputControl.errors && 
            Object.keys(inputControl.errors).length == 1 &&
            inputControl.errors.unMatchError ))
        {
            if(inputControl.value != this.MatchInput)
            {
                return { unMatchError: true };
            }
        }
        console.log("OutSide", inputControl.errors)
        return null;
    }
}

【问题讨论】:

    标签: angular typescript angular6 angular2-directives customvalidator


    【解决方案1】:

    你可以有一个 customValidator 像

    customValidator(params: any) {
        return (control: AbstractControl) => {
          ..your logic here..
          if (error)
            return { "customError": "Error in a function in component: The value is " + params }
          else
          {
              if (control.errors)
              {
                  if (control.errors.required)
                      return { "customError": "Error required"}
    
                  if (control.errors.pattern)
                      return { "customError": "Error pattern"}
                  ...
              }
          }
    
          return null;
        }
      }
    

    那你只问你的customError

    <span *ngIf="checkFiled.errors?.customError">
         {{checkFiled.errors?.customError}}
    </span>
    

    注意:errors.required,例如可能是真的,但你不能用它做任何事

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多