Angular Required Validation Example
March 05, 2020
This page will walk through Angular required validation example. Angular provides RequiredValidator
directive for required validation. In template-driven form, HTML elements use required
attribute for required validation and reactive form uses Validators.required
with FormControl
while creating FormGroup
. In reactive form Validators.requiredTrue
validates a control for true
value and we commonly use it for required checkboxes. In our example we will use required validation for input text, radio button, checkbox, and select element.
Angular 4 uses
novalidate
attribute by default in its form element at run time and hence while submitting form, HTML 5 validation will not work. If we are using Angular 2, we need to write novalidate
attribute in our form element to use Angular form validation. In Angular 4 template-driven form we can use ngNoForm
to enable HTML 5 validation. Here in our example we will provide demo for Template-driven form as well as Reactive form for Angular required validation. Now find the complete example step by step.
Contents
- Technologies Used
- Project Structure
- Input Text Required Validation
- Radio Button Required Validation
- Select Element Required Validation
- Checkbox Required Validation
- Example-1: Template-Driven Form Required Validation
- Example-2: Reactive Form Required Validation
- Run Application
- References
- Download Source Code
Technologies Used
Find the technologies being used in our example.1. Angular 9.0.2
2. Angular CLI 9.0.3
3. Node.js 12.5.0
Project Structure
Find the project structure of our demo application.angular-demo | |--src | | | |--app | | | | | |--domain | | | | | | | |--profile.ts | | | |--user.ts | | | | | |--services | | | | | | | |--user-service.ts | | | | | |--template-driven-form.component.ts | | |--template-driven-form.component.html | | |--reactive-form.component.ts | | |--reactive-form.component.html | | | | | |--app.component.ts | | |--app.module.ts | | | |--main.ts | |--index.html | |--styles.css | |--node_modules |--package.json
Input Text Required Validation
Find the code snippet for required validation in input text box.1. Using Template-driven form
We need to use
required
attribute in text input.
<input name="userName" [ngModel]="user.userName" required #uname="ngModel">
<div *ngIf="uname.invalid"> Name required. </div>
required
and minlength
validations together.
<input name="userName" [ngModel]="user.userName" required minlength="5" #uname="ngModel">
errors
. NgForm
defines errors
getter as following
get errors: ValidationErrors|null
errors
as following.
<div *ngIf="uname.errors?.required"> Name required. </div> <div *ngIf="uname.errors?.minlength"> Name must be at least 5 characters long. </div>
For required validation in reactive form we need to use
Validators.required
with FormControl
while creating FormGroup
.
userName: new FormControl('', Validators.required)
<input formControlName="userName">
get userName() { return this.userForm.get('userName'); }
<div *ngIf="userName.invalid"> Name required. </div>
Validators.required
with Validators.minLength
.
userName: new FormControl('', [Validators.required, Validators.minLength(5)])
errors
which is defined in FormGroup
as following.
get errors: ValidationErrors|null
errors
as following.
<div *ngIf="userName.errors?.required"> Name required. </div> <div *ngIf="userName.errors?.minlength"> Name must be at least 5 characters long. </div>
required
attribute with formControlName
as following.
<input formControlName="userName" required>
Radio Button Required Validation
Find the code snippet for required validation in radio button.1. Using Template-driven form
<input type="radio" value="male" name="gender" [ngModel]="user.gender" required #gender="ngModel"> Male <input type="radio" value="female" name="gender" [ngModel]="user.gender" required #gender="ngModel"> Female <div *ngIf="gender.invalid"> Gender required. </div>
gender: new FormControl('', Validators.required)
get gender() { return this.userForm.get('gender'); }
<input type="radio" value="male" formControlName="gender"> Male <input type="radio" value="female" formControlName="gender"> Female <div *ngIf="gender.invalid"> Gender required. </div>
required
attribute with formControlName
as following.
<input type="radio" value="male" formControlName="gender" required> Male <input type="radio" value="female" formControlName="gender" required> Female
Select Element Required Validation
Find the code snippet for required validation in select element.1. Using Template-driven form
<select name="profile" [(ngModel)]="user.profile" required #profile="ngModel"> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <div *ngIf="profile.invalid"> Profile required. </div>
profile: new FormControl('', Validators.required)
get profile() { return this.userForm.get('profile'); }
<select formControlName="profile"> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <div *ngIf="profile.invalid"> Profile required. </div>
required
attribute with formControlName
as following.
<select formControlName="profile" required> ------ </select>
Checkbox Required Validation
Find the code snippet for required validation in checkbox.1. Using Template-driven form
<input type="checkbox" name="isTCAccepted" [ngModel]="user.isTCAccepted" required #tc="ngModel"> <div *ngIf="tc.invalid"> Accept T & C. </div>
In reactive form
Validators.requiredTrue
validates a control for true
value. We commonly use it for required checkboxes.
isTCAccepted: new FormControl('', Validators.requiredTrue)
get isTCAccepted() { return this.userForm.get('isTCAccepted'); }
<input type="checkbox" formControlName="isTCAccepted"> <div *ngIf="isTCAccepted.invalid"> Accept T & C. </div>
required
attribute with formControlName
as following.
<input type="checkbox" formControlName="isTCAccepted" required>
Example-1: Template-Driven Form Required Validation
profile.tsexport class Profile { constructor(public prId: string, public prName: string) { } }
import { Profile } from './profile'; export class User { userName: string; gender: string; profile: Profile = null; isTCAccepted: boolean; constructor() { } }
import { Injectable } from '@angular/core'; import { User } from '../domain/user'; import { Profile } from '../domain/profile'; const profiles = [ new Profile('dev', 'Developer'), new Profile('man', 'Manager'), new Profile('dir', 'Director') ]; @Injectable() export class UserService { getPofiles(): Profile[] { return profiles; } createUser(user: User) { console.log('User Name: ' + user.userName); console.log('Gender: ' + user.gender); console.log('Profile: ' + user.profile.prName); console.log('T & C accepted?: ' + user.isTCAccepted); } }
import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { UserService } from './services/user-service'; import { User } from './domain/user'; import { Profile } from './domain/profile'; @Component({ selector: 'app-template', templateUrl: './template-driven-form.component.html' }) export class TemplateDrivenFormComponent implements OnInit { isValidFormSubmitted = false; user = new User(); allProfiles: Profile[]; constructor(private userService: UserService) { } ngOnInit() { this.allProfiles = this.userService.getPofiles(); } onFormSubmit(form: NgForm) { this.isValidFormSubmitted = false; if (form.invalid) { return; } this.isValidFormSubmitted = true; this.user = form.value; this.userService.createUser(this.user); this.user = new User(); form.resetForm(); } }
<h3>Template Driven Form</h3> <p *ngIf="isValidFormSubmitted" [ngClass] = "'success'"> Form submitted successfully. </p> <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)"> <table> <tr> <td>Name:</td> <td> <input name="userName" [ngModel]="user.userName" required minlength="5" #uname="ngModel"> <div *ngIf="uname.errors?.required && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> Name required. </div> <div *ngIf="uname.errors?.minlength && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> Name must be at least 5 characters long. </div> </td> </tr> <tr> <td>Gender:</td> <td> <input type="radio" value="male" name="gender" [ngModel]="user.gender" required #gender="ngModel"> Male <input type="radio" value="female" name="gender" [ngModel]="user.gender" required #gender="ngModel"> Female <div *ngIf="gender.invalid && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> Gender required. </div> </td> </tr> <tr> <td>Select Profile: </td> <td> <select name="profile" [(ngModel)]="user.profile" required #profile="ngModel"> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <div *ngIf="profile.invalid && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> Profile required. </div> </td> </tr> <tr> <td>Accept T & C </td> <td> <input type="checkbox" name="isTCAccepted" [ngModel]="user.isTCAccepted" required #tc="ngModel"> <div *ngIf="tc.invalid && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> Accept T & C. </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
Example-2: Reactive Form Required Validation
reactive-form.component.tsimport { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { UserService } from './services/user-service'; import { User } from './domain/user'; import { Profile } from './domain/profile'; @Component({ selector: 'app-reactive', templateUrl: './reactive-form.component.html' }) export class ReactiveFormComponent implements OnInit { isValidFormSubmitted = null; allProfiles: Profile[]; userForm = new FormGroup({ userName: new FormControl('', [Validators.required, Validators.minLength(5)]), gender: new FormControl('', Validators.required), profile: new FormControl('', Validators.required), isTCAccepted: new FormControl('', Validators.requiredTrue) }); user = new User(); constructor(private userService: UserService) { } ngOnInit() { this.allProfiles = this.userService.getPofiles(); } onFormSubmit() { this.isValidFormSubmitted = false; if (this.userForm.invalid) { return; } this.isValidFormSubmitted = true; this.user = this.userForm.value; this.userService.createUser(this.user); this.userForm.reset(); } get userName() { return this.userForm.get('userName'); } get gender() { return this.userForm.get('gender'); } get profile() { return this.userForm.get('profile'); } get isTCAccepted() { return this.userForm.get('isTCAccepted'); } }
<h3>Reactive Form</h3> <p *ngIf="isValidFormSubmitted && userForm.pristine" [ngClass] = "'success'"> Form submitted successfully. </p> <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <table> <tr> <td>Name: </td> <td> <input formControlName="userName"> <div *ngIf="userName.errors?.required && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> Name required. </div> <div *ngIf="userName.errors?.minlength && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> Name must be at least 5 characters long. </div> </td> </tr> <tr> <td>Gender:</td> <td> <input type="radio" value="male" formControlName="gender"> Male <input type="radio" value="female" formControlName="gender"> Female <div *ngIf="gender.invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> Gender required. </div> </td> </tr> <tr> <td>Select Profile: </td> <td> <select formControlName="profile"> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <div *ngIf="profile.invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> Profile required. </div> </td> </tr> <tr> <td> Accept T & C </td> <td> <input type="checkbox" formControlName="isTCAccepted"> <div *ngIf="isTCAccepted.invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> Accept T & C. </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
table { border-collapse: collapse; } table, th, td { border: 1px solid black; } .error { color: red; } .success { color: green; }
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-template></app-template> <app-reactive></app-reactive> ` }) export class AppComponent { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { TemplateDrivenFormComponent } from './template-driven-form.component'; import { ReactiveFormComponent } from './reactive-form.component'; import { UserService } from './services/user-service'; @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], declarations: [ AppComponent, TemplateDrivenFormComponent, ReactiveFormComponent ], providers: [ UserService ], bootstrap: [ AppComponent ] }) export class AppModule { }
Run Application
To run the application, find following steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your angular CLI application. To install angular CLI, find the link.
3. Run ng serve using command prompt.
4. Now access the URL http://localhost:4200
Find the print screen of the output. When we click on submit button without filling the form, we will get following output.

References
RequiredValidatorValidators
Form Validation