Reactive Form and Validation — Part 1

Parekh Dharmesh T
2 min readDec 4, 2021

Built-in validations

HTML attributes (i.e. required, maxlength etc..) are used for validations in template driven form.

This is fine for simple validation but what if our validations are dependent on some user or state of the application or business logic?

For example,

  • We can perform different validations for different type of user such as Admin, Normal user or Guest etc.
  • Based on some selection on UI such as if email checkbox is selected by user then email is required else mobile number is required.

Let us look at below topics, which are related to validation.

  • Setting built-in validation rules (i.e. required and max length)
  • Adjusting validation rule at run time
  • Custom Validators
  • Custom Validators with parameters
  • Cross field validation

Setting built-in validation rules

Below is the code of my customer component class and UI. we are using form Builder to create form model. our customer has total 5 input elements. all are textboxes except sendCatalog, which is type of checkbox.

Customer Validations
Customer Component Class (ngOnInit)

form builder group method has few overloaded versions. We have used one version in which we are passing key and value pair (name and default value).

To implement validation, we will use another overloaded version of group method. There is validator class that contains built-in validations. we will use this class and specify the name of desired validation rule. see below example. we have set required validation and maxlength rule for some of input fields.

Built-in Validations

If you want to specify more than one validation rules then you need to specify in the array. look at the validations set for last name.

Validation verification (error message)

We can see validation fail error message for both required and max length.

We will discuss next topic of validation named Adjusting validation rule at run time in next blog.

Adjust validations at run time → Part 2

--

--