I am validating an input, for which I have created 2 custom validators. what I can't get is to be able to relate each custom validator with a specific mat-error.
I leave my code below, and I appreciate any help
Custom validators:
ValidateNumbLength(control: AbstractControl) : ValidationErrors | null {
let numb = control.value;
let lengthNumb!: string;
if (numb != null){
lengthNumb = numb.toString();
}else {
return { 'numb invalid!': true };
}
if (lengthNumb.length == 1 || lengthNumb.length == 3 ) {
return null;
}if (lengthNumb.length == null){
return { 'numb invalid!': true };
}
else {
return { 'numb invalid!': true };
}
}
ValidateNnmbValue(control: AbstractControl) : ValidationErrors | null {
let numb = control.value;
let lengthNumb!: string;
if (numb != null){
lengthNumb = numb.toString();
}else {
return { 'numb invalid!': true };
}
if (numb == 0.5 || numb == 1.0 || numb == 1.5 ){
return null;
} if (lengthNumb.length == null){
return { 'numb invalid!': true };
}
else {
return { 'numb invalid!': true };
}
}
form control:
this.nominalSizeGroup = this._formBuilder.group({
numb: ['', [ Validators.compose([Validators.required, Validators.min(0)]), this.ValidateNumbLength, this.ValidateNnmbValue]],
});
<mat-error *ngIf="(nominalSizeGroup.get('numb')?.touched || nominalSizeGroup.get('numb')?.dirty) && nominalSizeGroup.get('numb')?.invalid && nominalSizeGroup.get('numb')?.hasError('ValidateCoolingTomsLength')">
Cooling tons must be 1 or 3 characters.
</mat-error>
<mat-error *ngIf="nominalSizeGroup.get('numb')?.invalid">
You have entered an incorrect value.
</mat-error>
CodePudding user response:
The key you return with your validator is the name of the error that the input will have. In your case they key is 'numb invalid!'
for all cases. So to check for these errors it's:
nominalSizeGroup.get('numb')?.hasError('numb invalid!')
If you want different messages for different cases, you need to rename the errors:
ValidateNumbLength(control: AbstractControl) : ValidationErrors | null {
let numb = control.value;
if (!numb) return { numbIsFalsey : true };
const lengthNumb = numb.toString();
if (lengthNumb.length === 1 || lengthNumb.length === 3 ) {
return null;
else {
return { wrongLength: true };
}
}
<mat-error *ngIf="nominalSizeGroup.get('numb')?.hasError('numbIsFalsey')">
Please enter a value.
</mat-error>
<mat-error *ngIf="nominalSizeGroup.get('numb')?.hasError('wrongLength')">
Cooling tons must be 1 or 3 characters.
</mat-error>
Just a side note: you should never use ==
for equality, that only exists for legacy code, ===
is the proper way.