In my previous blog, I went over creating an angular reactive form and adding some basic validation. In this blog post, I will go over how to make your custom validator.
The first thing we need to do is clone the previous Github code. Once you have done that, open the contact-form.component.ts
file.
First, we need to import AbstractControl
, so on line 2, add AbstractControl
to the import. It should look like this:
import { AbstractControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
Now let's make a new function that we will use to validate phone numbers in our forms. Here is the function:
private phoneNumberValidator(
control: AbstractControl
): { [key: string]: any } | null {
const valid = /^\d+$/.test(control.value);
return valid
? null
: { invalidNumber: { valid: false, value: control.value } };
}
The function above will use a regular expression to validate the user input. The current regular expression will only accept numbers, and if the user input is valid, it will return null. Otherwise, it will return an object with the error.
Now let's make a helper function that we will use to get the error message.
get phoneNumber() {
return this.contactForm.get('phoneNumber');
}
Now, if we open our contact-form.component.html
file, we can add the following line of code on line 11:
<p>
Phone Number:
<input type="text" formControlName="phoneNumber">
<br/>
<span class="error" *ngIf="phoneNumber.errors?.invalidNumber">
Invalid phone number
</span>
</p>
As you can see, we now have red text saying Invalid phone number under the phone number input. Type a number in the field, and you will see that the error text goes away.
Here is the link to the Github repo.
As always, feel free to reach out if you have any questions or comments.