After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer.
The desired functionality for the custom validator is to restrict input to be only numeric and specifically three-digit numbers such as 838, 892, 183, 234, and so forth.
Currently, the validator also accepts characters which is not the intended behavior.
threeNumbers(control: FormControl) {
if (control.value && !/[0-9\+\-\ ]/.test(control.value) && control.value.length < 3) {
return { 'greater than 3 numbers': true };
}
return null;
}
}
this.courseForm = this.fb.group({
username: [null, [Validators.required, this.threeNumbers, Validators.maxLength(3)]],
email: [null, [Validators.required, Validators.pattern('([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_.-]+)\\.([a-zA-Z]{2,5})')]],
address: [null, [Validators.required, Validators.minLength(10), Validators.maxLength(100)]],
select: [null, [Validators.required]]
});
// html template
<form class="form-horizontal" (ngSubmit)='onSubmit()' [formGroup]='courseForm'>
<div class="form-group">
<label for="inputUsername" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUsername" placeholder="Username" formControlName="username" name="name"
[ngClass]="{inValid: !courseForm.get('username').valid && courseForm.get('username').touched, valid: courseForm.get('username').valid && courseForm.get('username').touched}">
<span class="help-block" *ngIf="!courseForm.get('username').valid && courseForm.get('username').touched">Please enter a valid username</span>
</div>
</div>