Part 9 : validations in angular 2
In this tutorial we will study how to implement validations in angular 2 project.
The validation for form is explained in this video.
Covers the basic concept of model based validations in angular 2.
The validation for form is explained in this video.
Covers the basic concept of model based validations in angular 2.
App Module Code
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from '../../Views/App/app.component';
import { ReactiveFormComponent } from '../../Views/ReactiveForm/reactive.form';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ AppComponent,ReactiveFormComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Validation code
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'reactive-form',
template: `<h1>{{Title}}</h1><hr/>
<form [formGroup]='MyForm' (ngSubmit)='SaveData(MyForm.value)'>
<label>First Name</label><br/>
<input formControlName='FirstName' type='text' /><br/>
<span style="color:red" *ngIf="!MyForm.controls['FirstName'].valid && MyForm.controls['FirstName'].touched">
First Name required</span><br/>
<label>Last Name</label><br/>
<input formControlName='LastName' type='text' /><br/>
<span style="color:red" *ngIf="!MyForm.controls['LastName'].valid">Max length should be 6</span><br/>
<button [disabled]='!MyForm.valid' type='Submit' >Save</button>
</form>
`,
})
export class ReactiveFormComponent {
Title: string;
MyForm: FormGroup;
constructor(fb: FormBuilder) {
this.Title = "Reactive Form";
this.MyForm = fb.group({
'FirstName': ['', Validators.required],
'LastName': ['',Validators.maxLength(6)]
})
}
SaveData(form: any) {
console.log(form);
}
}
Click here to download validation project in angular 2
No comments