Angular2 Forms Tutorial: Validating Required Fields

Angular2 Form Validation
Angular2 Form Validation

In this tutorial I’ll give you a simple example of how to validate a form with angular2. As you can see in the image, the example consists of a form with two required fields, the form can only be submitted if both fields are valid.

I’m going to use bootstrap for styling, if you want your form to look like the image above you just have to add the follwoing scripts to your index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>

Now let’s take a look at our component:

import {Component} from '@angular/core';
 
@Component({
  selector: 'form-validation-example',
  template: `
     <form (ngSubmit)="submit()" >
	<div class="form-group has-feedback" 
	     [ngClass]="{ 'has-error' : !firstNameControl.valid && submitAttempt }">
           <label class="control-label" >First Name</label>
           <input type="text" class="form-control"
	      name="firstName" [(ngModel)]="firstName" #firstNameControl="ngModel" required>
           <span *ngIf="!firstNameControl.valid && submitAttempt"
	      class="glyphicon glyphicon-remove form-control-feedback" ></span>
	</div>
	<div class="form-group has-feedback" 
	     [ngClass]="{ 'has-error' : !emailControl.valid && submitAttempt }">
	   <label class="control-label">E-mail</label>
	   <input type="text" class="form-control"
              name="email" [(ngModel)]="email" #emailControl="ngModel" required>
           <span *ngIf="!emailControl.valid && submitAttempt"
	      class="glyphicon glyphicon-remove form-control-feedback" ></span>
	</div>
	<button type="submit" class="btn btn-default" (click)=initSubmit()>Submit</button>
     </form>
  `
})
export class FormComponent {
      submitAttempt = false;
 
      initSubmit(){
	  this.submitAttempt = true;
      }
 
      submit(){
 	  console.log('success!');
      }
}

This is just a regular form, what makes the fields required is the required attribute at the end of each input, just using this attribute will already be enough to prevent the form from submitting, but it won’t change the field style as shown in the demo at the beginning.

To be able to change the style of the input we first have to know if the field is valid or not, an easy way to achieve this is to declare a template reference variable for each field, if you take a look at the code you’ll see the attribute #firstNameControl="ngModel" on the first input and #emailControl="ngModel" on the second, that’s how template reference variables are declared. Now I can use the names firstNameControl and emailControl to access properties of my inputs on other parts of my template, but the only one that matters to us is the property valid.

We also need a way to determine if the submit button was clicked or not, that’s why I’ve created the variable submitAttempt, it’s false by default but it’ll be set to true once the button is clicked.

By using the template reference variables and the submitAttempt variable we can now write the condition that changes the styles, which is !firstNameControl.valid && submitAttempt for the first field and !emailControl.valid && submitAttempt for the second. These conditions are used to add the bootstrap class has-error on each form-group and also to render the icon at the end of the input.

Lastly we have the submit() function which will just print the string ‘success!’ on the console, this function will only be called if both fields are valid.

Recommended for you

Interacting with Child Components in Angular2 There are lots of situations where we have to divide a component into several sub-components, resulting in a parent with N child components that somehow have to interact with the parent, like for example a menu component like this: In this case the menu-componen...
Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application. Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host comp...
Angular2 error: Error in ./AppComponent class AppComponent_Host – inline template:0:0 caused b... If you're seeing this error when you run your application it's probably because you're trying to use http.get without importing the HttpModule. This is what the error looks like on the browser console: core.umd.js:5995 EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline temp...
Angular2 Tutorial: Creating Custom Pipes Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don't meet our needs, that's when we have to create custom pipes. This will be a very quick tutorial in which I'll give you an example ...

Leave a Reply

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

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>