I love that Material input has a built in validator for email
myFormControl = new FormControl('', [
Validators.required,
Validators.email
]);
But there's not one for phone numbers. In the above myFormControl, I changed the email Validator to a pattern to broadly handle phone numbers...
myFormControl = new FormControl('', [
Validators.required,
Validators.pattern('^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$')
]);
However, when I attempt to create an HTML to handle phone number input...
<mat-form-field class="form-field">
<input matInput placeholder="Phone Number" [formControl]="myIDFormControl"
[errorStateMatcher]="matcher">
<mat-hint>Must be a valid phone number</mat-hint>
<mat-error *ngIf="myIDFormControl.hasError('pattern') && !myIDFormControl.hasError('required')">
Please enter a valid phone number
</mat-error>
<mat-error *ngIf="myIDFormControl.hasError('required')">
Phone number is <strong>required</strong>
</mat-error>
</mat-form-field>
I get this error...
ERROR SyntaxError: "nothing to repeat"
I think it has to do with the formatting of the RegEx in the Validators.pattern. However, I have tried about 5 different canned RegEx's for phone numbers and they all seem to produce this error.
What is a pattern that will work in Angular6 Material for this need?
Aucun commentaire:
Enregistrer un commentaire