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
The Form Validation of multiple parameters or multiple conditions should be composed as single validator otherwise you will get observable or promise error:
phone: ['', Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],
try this working sample code :
component.html
<div class="container">
<form [formGroup]="myForm"
(ngFormSubmit)="registerUser(myForm.value)" novalidate>
<div class="form-group" [ngClass]="{'has-error':!myForm.controls['phone'].valid}">
<label for="phone">Email</label>
<input type="phone" formControlName="phone" placeholder="Enter Phone"
class="form-control">
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('minlength')">
Your phone must be at least 5 characters long.
</p>
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('maxlength')">
Your phone cannot exceed 10 characters.
</p>
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('required') && myForm.controls['phone'].dirty">
phone is required
</p>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>
</div>
</form>
</div>
component.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
export class AppComponent implements OnInit {
myForm: any;
constructor(
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.myForm = this.formBuilder.group({
phone: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
});
}
}
This trick will be helpful
In .html file
<input type="text" (keyup)="onKeyUp($event)" formControlName="phone" placeholder="Phone Number">
In .ts file
The below code restrict string characters
public onKeyUp(event: any) {
const NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
let newValue = event.target.value;
let regExp = new RegExp(NUMBER_REGEXP);
if (!regExp.test(newValue)) {
event.target.value = newValue.slice(0, -1);
}
}
and other validation
phone: ['', Validators.compose([
Validators.required,
Validators.pattern('^[0-9]{0,30}$')])
])],
The above pattern code allow number upto 30 digits. If you want minimum two digits, you can do like this
Validators.pattern('^[0-9]{2,30}$')
Keep <input type="number" />
and just transform the int values to strings.
const phoneControl: FormControl = this.myForm.controls.phone;
// Do not forget to unsubscribe
phoneControl.valueChanges.subscribe(v => {
// When erasing the input field, cannot read toString() of null, can occur
phoneControl.setValue((v && v.toString()) || null, { emitEvent: false });
});
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)])]
});
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;
};
}
}