I am trying to develop a contact form, I want user to enter phone number values between length 10-12.
Notably same validation is working on Message field, Its only number field which is giving me trouble.
I found this answer but it is of no use for me.
I have code like following :
HTML :
<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
<input type="number" formControlName="phone" placeholder="Phone Number">
<input type="text" formControlName="message" placeholder="Message">
<button class="button" type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
TS :
this.myForm = this.formBuilder.group({
phone: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(12)]],
message: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(100)]]
});`
Update 1 :
phone: ['', [Validators.required, Validators.min(10000000000), Validators.max(999999999999)]],
Used it like following and worked perfectly :
phone: ['', [Validators.required, customValidationService.checkLimit(10000000000,999999999999)]],
customValidationService :
import { AbstractControl, ValidatorFn } from '@angular/forms';
export class customValidationService {
static checkLimit(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
return { 'range': true };
}
return null;
};
}
}