Мне нужно сравнить, совпадает ли вводимый текст сначала со встроенными ошибками, такими как 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;
}
}