【发布时间】: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