Use FormBuilder to Validating Form Input In Angular

Form validation guarantees that every user input is correct and complete. This section will go through how to add a single validator to a form control and how to display the overall form status.

Follow these steps to use form validation:

In your form component, include a validator function.
Insert the validator into the form’s field.
Create logic to deal with the validation status.
Making a field necessary is one of the most popular validations. The following example demonstrates how to add a necessary validation to the firstName control and display the validation result.

Add a Validator Function.
Validator routines for typical use scenarios are included in reactive forms. Based on the validation check, these functions get a control to validate against and return an error object or a null value.

As seen below, import the Validators class from the @angular/forms package.

File name : employeeDetails-editor.component.ts

import { Validators } from '@angular/forms';


Make a field mandatory.
Include Validators.
The second item in the array for the firstName control is required in the EmployeeDetailsEditor component static function.

File name : employeeDetails-editor.component.ts

emplyeeDetailsForm ={
  firstName: ['', Validators.required],
  lastName: [''],
    street: [''],
    city: [''],
    state: [''],
    zip: ['']


HTML5 has a number of built-in characteristics for native validation, including needed, minlength, and maxlength. These optional properties can be used on your form input components. To the firstName input element, add the needed property.

<input type="text" formControlName="firstName" required>


These HTML5 validation elements must be used in conjunction with the built-in validators offered by Angular’s reactive forms. Using them together avoids errors from occurring when the expression is modified after the template has been verified.

Show Form Status
A mandatory field may now be added to the form control. Its original status is incorrect. This incorrect state spreads to the parent form group element, rendering it invalid. The status property of the form group instance provides access to the current status of the form group instance.

Using interpolation, display the current state of employeeDetailsForm.

File name : employeeDetails-editor.component.html

  Form Status: {{ employeeDetailsForm.status }}


Because employeeDetailsForm is invalid owing to the needed firstName form control, the Submit button will be blocked. The form becomes legitimate once you fill out the firstName entry, and the Submit button is activated.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories