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)]]
});`
For a
number
field, you can validate min and max values using built in Angular validation, like this:.ts
html
I have a trick that 100% work.
Define input of type 'text' and not 'number'.
For eg:
<input placeholder="OTP" formControlName="OtpUserInput" type="text">
Then use pattern which is part of Validation.
Like :
It means we define input type text that is suitable for min length and we also define pattern(validation) for numeric value so that we can achieve both validation.
Remaining code :
The Form Validation of multiple parameters or multiple conditions should be composed as single validator otherwise you will get observable or promise error:
If you want to validate a field by multiple validators then, You should try this
Use Compose() method, compose multiple validators into a single function.
Update .TS file as below,
this.myForm = this.formBuilder.group({ phone: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(12)])], message: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(100)])] });