自定义指令一次显示一个内置和自定义错误

时间:2019-01-25 06:37:22

标签: angular typescript angular6 angular2-directives customvalidator

我需要比较输入文本是否首先与所需的,最小长度,最大长度,模式等内在错误匹配,然后检查输入是否也满足我的自定义条件。

要应用自定义条件,我使用了“自定义验证程序指令”。当我使用此指令时,它一次显示多个错误消息。我对所有组合都感到厌倦,但仍然无法一次仅收到一条错误消息。

所以我需要编写一个通用指令,该指令可以显示:
1)所有内在的错误也会显示出来,然后显示我们的自定义错误。
2)一次仅显示一个错误
3)首先应为内置错误(如要求的,样式等)赋予优先级,然后应检查我们的自定义条件。

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;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用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>

注意:所需的错误,例如可以是真的,但是你什么也做不了