Checkbox Mandatory on Click Continue Angular 2

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">          

The validation error message can be displayed as following

<div *ngIf="uname.invalid">  	  Name required.  </div>          

Now we will use required and minlength validations together.

<input name="userName" [ngModel]="user.userName" required minlength="5" #uname="ngModel">          

For different validation error messages, we should use errors. NgForm defines errors getter as following

get errors: ValidationErrors|null          

Find the error messages using 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>          

2. Using Reactive form

For required validation in reactive form we need to use Validators.required with FormControl while creating FormGroup.

userName: new FormControl('', Validators.required)          

In HTML template we will create text input as following.

<input formControlName="userName">          

For validation error message, first we need to create a getter as following.

get userName() {      return this.userForm.get('userName'); }          

Then show validation error message as following.

<div *ngIf="userName.invalid">      Name required.  </div>          

Now we will use Validators.required with Validators.minLength.

userName: new FormControl('', [Validators.required, Validators.minLength(5)])          

To show separate validation error messages, we will use errors which is defined in FormGroup as following.

get errors: ValidationErrors|null          

Find the error messages using 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>          

For required validation in reactive form, we can also use 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>          

2. Using Reactive form

gender: new FormControl('', Validators.required)          

Getter method:

get gender() {     return this.userForm.get('gender'); }          

HTML template code snippet:

<input type="radio" value="male" formControlName="gender"> Male <input type="radio" value="female" formControlName="gender"> Female  <div *ngIf="gender.invalid">    Gender required.  </div>          

For required validation in reactive form, we can also use 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>          

2. Using Reactive form

profile: new FormControl('', Validators.required)          

Getter method:

get profile() {     return this.userForm.get('profile'); }

HTML template code snippet:

<select formControlName="profile">    <option *ngFor="let prf of allProfiles" [ngValue]="prf">        {{ prf.prName }}    </option> </select>  <div *ngIf="profile.invalid">    Profile required.  </div>          

For required validation in reactive form, we can also use 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>          

2. Using Reactive form
In reactive form Validators.requiredTrue validates a control for true value. We commonly use it for required checkboxes.

isTCAccepted: new FormControl('', Validators.requiredTrue)          

Getter method:

get isTCAccepted() {     return this.userForm.get('isTCAccepted'); }          

HTML template code snippet:

<input type="checkbox" formControlName="isTCAccepted">  <div *ngIf="isTCAccepted.invalid">       Accept T & C. </div>          

For required validation in reactive form, we can also use required attribute with formControlName as following.

<input type="checkbox" formControlName="isTCAccepted" required>          

Example-1: Template-Driven Form Required Validation

profile.ts

export class Profile {     constructor(public prId: string, public prName: string) {     } }          

user.ts

import { Profile } from './profile';  export class User {     userName: string;     gender: string;     profile: Profile = null;     isTCAccepted: boolean;     constructor() {     } }          

user-service.ts

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);    } }          

template-driven-form.component.ts

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();   } }          

template-driven-form.component.html

<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.ts

import { 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');   } }          

reactive-form.component.html

<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>          

styles.css

table {     border-collapse: collapse; } table, th, td {     border: 1px solid black; } .error {     color: red; } .success {     color: green; }          

app.component.ts

import { Component } from '@angular/core';  @Component({    selector: 'app-root',    template: ` 		<app-template></app-template> 		<app-reactive></app-reactive>              ` }) export class AppComponent { }          

app.module.ts

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.

Angular Required Validation Example

References

RequiredValidator
Validators
Form Validation

Download Source Code

smithmintwoubity.blogspot.com

Source: https://www.concretepage.com/angular-2/angular-2-4-required-validation-example

0 Response to "Checkbox Mandatory on Click Continue Angular 2"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel