I made an angular 6 custom validators to check if a user entered the 3 required digits or not. Here is my input:
<mat-form-field appearance="outline" color="warn">
<mat-label>Last 3 digits</mat-label>
<input matInput type="text" formControlName="last_three_digits" placeholder="Last 3 digits">
</mat-form-field>
And here is how I declare it in reactive form:
'last_three_digits': new FormControl('', [Validators.required, validatePositiveNotNull, validateLengthThree])
I tried to add Validators.pattern("[0-9 ]*")
but it keep letting the user to add -
or +
or =
or /
.
I just need to strict into number of length = 3.
Here is the script:
export function validateLengthThree(control: AbstractControl)
{
if(control.value==null || control.value==undefined)
{
return { validPositive: true}
}
else if(control.value.length<3 && control.value!=null && control.value!=undefined)
{
return { validPositive: true}
}
else if(control.value.length>3)
{
return { validPositive: true}
}
return null;
}
I tried to change the type of input to number
but still the same.
I used this pattern /^\d+$/
from this answer on stack, and the input still accepting the special characters and validating the form.
P.S. I added the null
and undefined
conditions in my custom validators, because when I focus out from this input, and while it's empty, it throw an error saying that it can't run on null values.