Reputation: 2275
I am trying to validate a minLength
but it does not recognize it, for that I am using a function. I have also tried it directly in the template but I do not get any results.
myComponent.html
<mat-form-field>
<input matInput placeholder="Ingresa tu celular" type="number" formControlName="celular">
<mat-error *ngIf="forma.controls['celular'].invalid">{{ errorCelular() }}</mat-error>
</mat-form-field>
myComponent.ts
celular: [ '', [Validators.required, Validators.minLength(9)] ],
errorCelular() {
return this.forma.controls.celular.hasError('required') ? 'El celular es necesario.' :
this.forma.controls.celular.hasError('minlength')? 'Mínimo 9 caracteres': '';
}
Upvotes: 0
Views: 1611
Reputation: 6894
minLength
doesn't work in previous versions of angular with type="number"
. Check this Github issue why.
If you do not need the input to be of type="number"
, change it to type="text"
and it should work. If you need it to be of type number, then you should use a custom Validator which checks that the number is greater than the minimum 9 digit number (100000000)
import { AbstractControl } from '@angular/forms';
function customMinValidator(control: AbstractControl): { [key: string]: boolean } | null {
if (control.value !== undefined && (isNaN(control.value) || control.value >= 100000000 )) {
return { 'customMin': true };
}
return null;
}
and then use it like -
celular: [ '', [Validators.required, customMinValidator] ]
Note: The above is just an example on "how" to use it. It won't work exactly as expected as the condition would fail for a number like 000112313, which has a minLength of 9 as desired. But this should give you a fair idea on how to tackle it.
Upvotes: 3