I need to compare if the input text first matches with the inbuilt errors like required, minlength, maxlength, pattern and then check if input satifies my custom condition as well.
To apply custom condition I have used Custom validator Directive. When I use this directive it displays more than one error message at a time. I tired with all combinations but still not able to get only one error message at a time.
So i need to write a generic Directive which can display :
1) All inbuilt errors also and then display our custom errors.
2) Display only one error at a time
3) First Priority should be given for inbuilt erros like required, pattern etc and then our custom condition should be checked.
HTML Code
<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 Code
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;
}
}