You make pattern forms. Please refer to this simple plunk
<h1>Employee Form</h1> <form #personForm="ngForm" (submit)="personFormSubmit(personForm)" novalidate> <div> <div> <input id="nameInput" type="text" name="name" ngControl="name" required minlength="2" maxlength="35" [(ngModel)]="person.name" /> </div> </div> <div> <button type="submit">Submit</button> </div> <div style="color: red">{{validationMessage}}</div> </form>
and then the controller:
import { Component } from '@angular/core'; import { FORM_DIRECTIVES, ControlGroup, Control, Validators, FormBuilder, Validator, } from '@angular/common'; import 'rxjs/Rx'; export class Person { id: number; name: string; } @Component({ selector: 'my-app', directives: [FORM_DIRECTIVES], templateUrl: 'app/app.component.html' }) export class AppComponent { person: Person; validationMessage: string; constructor() { this.person = new Person(); this.validationMessage = ""; } personFormSubmit(personForm: ControlGroup) { if (personForm.valid) { this.validationMessage = "Form Is Valid"; } else { this.validationMessage = "Form Is Not Valid"; } } }
If you want to move on to more complex dynamic validation, it would be better to convert to Model-Driven Forms. How with this plunk
Eric weiss
source share