Angular Form Validation Example

Here you learn how to validate form in angular JS, Form validation example in Angular, also learn about form, formgroup, formbuilder, formcontrol etc.

As we know in angular we can extend html object properties , so here we learn form tag extending properties.

There are two type of form in Angular JS Framework.
  • Template-driven form
    Template-driven forms are basically ready to use form for business operation like Login, Register, schedule meeting etc.
  • reactive form
    Reactive forms provide a model-driven approach.
    import { ReactiveFormsModule } from '@angular/forms';

It would be nice if you have some knowledge of JavaScript , CSS and TypeScript before you start learn learning Angular.

To understand how form works in Angular, we need to understand how component is written in typescript file, let's look at the example.

Angular Form Designing

First we learn angular syntax in form, and how to submit values, then we learn validation part.

Angular form submit example
Here we have created a simple form in html file called "addstudent.component.html", While creating any component there will be always typeScript file associated with html file, you need to understand the relation and how reference is being added

Here is how we can add formgroup name in angular form, in form tag we need to add [formgroup]="groupName". this is type of form name, to indentify the form and its control.

<form [formgroup]="studentForm"> </form>

Now, let's look how a form will look like with formgroup.

File name: addstudent.component.html
<form (ngsubmit)="saveStudent()" [formgroup]="studentForm" novalidate>
<div class="col-md-4">
Fullname:   <input class="form-control" type="text" formcontrolname="fullname" [(ngmodel)]="fullname">
</div>
<input type="submit" value="Add Student" class="btn btn-success" />
</form>

So in above form you can see something new, which were not there in earlier html form, let’s see what those tags are..!

(ngsubmit)
here we define the method name to be executed when the form is submitted.

novalidate:
this is actually HTML 5 attribute, indicates form-data not be validated upon submission, You can use "novalidate" when you need your own AngularJS custom validation

Step 1: Import all required angular namespace in addstudent.component.ts (File name)

import { Component, OnInit,Inject } from '@angular/core';  
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';  
import { Router } from '@angular/router'; 
import 'rxjs/add/operator/map';  
import 'rxjs/add/operator/catch';  
import 'rxjs/add/observable/throw';  
import { NgForm, FormBuilder, FormGroup, Validators, FormControl, FormsModule } from '@angular/forms';  

Step 2: Set the html template url, you also can set CSS file for this template (in case you have separate CSS file for each component)

@Component({   
    templateUrl: './addstudent.component.html'
})

Step 3: Now create the component class. Notice we have created two things inside the class, 1) FormGroup and 2) saveStudent() method

export class CreateStudentComponent
{
    studentForm: FormGroup = new FormGroup({
        fullname: new FormControl(''),
        address: new FormControl(''),
        email: new FormControl(''),
        mobile: new FormControl('')
        
    });
     public saveStudent() {
        alert("saveStudent() executed");
        alert(this.studentForm.controls["fullname"].value);        
    }
}

Notice how FormGroup has been used and in saveStudent() method how user input value has been captured.
here is the code this.studentForm.controls["fullname"].value

So far you have seen how to design a basic angular form and Formcontrol inside the form, now we learn how to check angular form validation and send those validated values to API method.

How to Check Angular Form Validation

Here we learn how to use validation with formBuilder at the time of initialization (ngOnInit) in TypeScript file.
first we have to implement OnInit in component class.

export class CreateStudentComponent implements OnInit{
ngOnInit() {
this.studentForm = this.formBuilder.group({
fullname: ['', Validators.required, Validators.maxLength(50)],
address: ['', Validators.required, Validators.maxLength(100)],
email: ['', [Validators.required, Validators.email]],
mobile: ['', [Validators.required, Validators.minLength(10)]]
});
    }
}

At the time of initialization we need to set the data type, data length etc for each fields in form.

 
AngularJS Form Validation
Learn Angular JS: JavaScript framework for single page application.
JavaScript Framework
Angular JS Examples | Join Asp.Net MVC Course