How to add validation rule to Angular Reactive form using form Builder


In Angular we can add specific rules to a form input field, such as required, minlength etc and then apply visual change in and user friendly feedback.

In reactive form all the these done in component level. We already learn how to capture data in a angular form, if you miss the post here is the link.

Setting the rule

For setting the rule we can use the second argument of Group of form Builder as follows (in app.component.ts)

  • import the Form Builder and Validators
  • Inject the dependency in constructor
  • Use the builder service to create group
  • Pass the Validator as the second argument to the Group
import { FormBuilder, Validators } from "@angular/forms";
....
constructor(private fb: FormBuilder) {}
.....
todoForm = this.fb.group({
    item: ["builder todo",  Validators.required],
    description: ["", Validators.required],
  });

Have multiple rules ?

In case you have multiple rules for the control, can use the validation rule as a list

  todoForm = this.fb.group({
    item: ["buikder todo", [Validators.required, Validators.minLength(4)]],
    description: ["", Validators.required],
  });

That is all about validation. Following angular form post may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.