Reactive Forms and Validations- Part 3

Parekh Dharmesh T
3 min readDec 6, 2021

Custom Validator

This is again in continuation of my previous blog of Reactive forms and validation.

Angular provides only basic validators such as required, maxlength and pattern. though we can do lot using pattern but there are times when we need custom validation rule. We can define custom validation rule with a custom validator.

In simple word, validator is a function. It always takes one parameter, FormGroup or FormControl that is to be validated.

Let us look at the syntax. Validator function returns object or null if it is valid. return value is comprised of a key and value pair where key is the string and value is a Boolean.

Custom Validator function Syntax

Let us build custom validator to understand it in details. let me add one rating field in our custom sign up form. it’s valid value range is 1 to 5. we need to develop custom validator to validate user input value for rating.

In component class, we have set the default value for rating is null as it is number field.

Rating FormControl added with default value = null

We will build custom numeric range validator and it will handle our validation rule. Assume that this validation is only used by our custom sing-up component hence we are adding function in component class itself. if it is used by other parts of the application then it is better to put it in another file. so that it can be shared across the application code.

Custom validator name — ratingRange

ratingRange function

Now we have to now just add ratingRange validator in rating FormControl. that’s it.

Now let us verify our custom validator from UI by entering invalid and valid values.

Entered 25 that invalid value and we can see error message

This is all about custom validator. In real world application, we should place all custom validators in their own file and can be reused from different parts of the application.

Cross field validation → Part 4

--

--