Vassiliki Dalakiari
ITNEXT
Published in
4 min readSep 12, 2020

--

Angular’s popular Reactive Forms functionality comes with a Validator class that contains some very basic built-in validators for form fields, such as required, email, minLength and maxLength. But sometimes we need to validate more complex rules that cannot be covered with the basic ones.

Fortunately, it is very easy to create and assign a custom validator to a form field.

Example case

I want to create a form that contains a custom reactive form field to accept phone numbers. You can see how to create a custom reactive form field with Material Design here.

My field has two parameters: the country and the actual phone number.

When I choose a country from the dropdown, my program converts this country into a country code.
For example: 30 for Greece, 81 for Japan, 1 for USA etc

Example phone number object:

{
"country_code" : "30",
"national_number" : "2123456789",
"flag_class" : "gr"
}

I want to create a validator that checks if country code exists and if the number entered is a valid number for this country.

Create a custom Validator

Let’s start by creating a new file. I recommend that you create a new folder where you keep all your validators.

First of all, I will create and export an arrow function that accepts a FormControl parameter and returns a ValidatorFn.

export const phoneNumberValidator: ValidatorFn = (control: FormControl) => {}

Every time I set this validator to a form control, my function will have this control as a parameter.
My function must return:

  1. a {[key]: [value]} expression, if an error exists
  2. null if it’s valid

In my example I use google-libphonenumber library for two reasons:

  1. to get the country code
  2. to check if number provided is a valid phone number for the selected country

In this article, I will focus on the second one.

Use google-libphonenumber inside the validator

--

--