How to validate Angular Reactive form


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.ts. We already learn how to capture data in a angular form, if you miss the post here is the link.

Setting the rule

Reactive form that uses formGroup you just specify the rule as follows, for formBuilder forms the rules are specified at component level, so that this step is not required.

<form [formGroup]="todoForm" required  novalidation > 
 <input type="text" class="form-control" formControlName="item">
</form>

This will tell the template this field is a compulsory field. If the user leave it blank it will return invalid props as true.

Applying styles

We can bind class according to validation status.

  [class.is-invalid]="item.invalid && item.touched" 

This will add red boarder for the input field , if the user leave it blank and user clicked the item and then tap outside the box.

You may wondering where the item coming from ? It is getter in the component which make the template code shorter

  get Item(): any {
    return this.todoForm.get("item");
  }

feedback

A good app come with user friendly feed back, we conditionally place a small using the validation rules.

 <small class="text-danger" *ngIf="Item.errors.required"  >The title can't be blank</small>

Multiple feedback

Suppose you have added multiple rules to a text field, when it become invalid there can be two chances. So we need to conditionally check and then show appropriate feedback.

This can be done using a div and two small tag with ngIf conidtional

 <div *ngIf="Item.invalid && Item.touched" class="alert-danger" >
         <small class="text-danger" *ngIf="Item.errors.required"  >The title can't be blank</small>
         <small class="text-danger" *ngIf="Item.errors.minlength"  >Title should contain at least 4 letter</small>
      </div>

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.