How to validate Angular 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 template driven form all the these done in component template. We already learn how to capture data in a angular form, if you miss the post here is the link.

Setting the rule

This is the simple step you just specify the rule in <input> tag.

 <input type="text" #item="ngModel" required name="item"  class="form-control"   [(ngModel)]="todoModel.item">

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.

feedback

A good app come with user friendly feed back, we conditionally place a small using the validation rules. The d-none class help us to hide the component when the input is valid

<small class="alert-danger" [class.d-none]="item.valid">title is required</small >

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.