In my project, I am facing a challenge where I need to compare the input text with a series of inbuilt errors such as required, minlength, maxlength, and pattern. Additionally, I also need to validate the input against a custom condition using a Custom Validator Directive. However, when using this directive, multiple error messages are displayed simultaneously which is not desired. Despite trying various combinations, I have been unable to display only one error message at a time.
Therefore, I am looking to develop a generic Directive that can achieve the following objectives:
1) Display all inbuilt errors along with our custom errors.
2) Show only one error message at a time.
3) Prioritize inbuilt errors like required and pattern before validating against our custom condition.
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
{
// There is a need to implement a proper condition to prioritize checking for inbuilt errors. If any inbuilt error is present, the 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;
}
}