Home  >  Angular 4

Angular 2/4 minlength and maxlength Validation Example

By Arvind Rai, November 01, 2017
This page will walk through Angular minlength and maxlength validation example. In template-driven from we need to use minlength and maxlength attributes with ngModel in HTML elements such as text input. In reactive form we need to pass Validators.minLength and Validators.maxLength in FormControl while creating FormGroup. We can also use minlength and maxlength attributes with formControlName in reactive form.
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 min and max length validation. Now find the complete example step by step.

Technologies Used

Find the technologies being used in our example.
1. Angular 4.2.4
2. Angular CLI 1.4.9
3. TypeScript 2.3.3
4. Node.js 6.11.0
5. NPM 3.10.10

Project Structure

Find the project structure of our demo application.
angular-demo
|
|--src
|   |
|   |--app 
|   |   |
|   |   |--user.ts
|   |   |--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 

minlength Validation

Angular provides MinLengthValidator directive to validate minimum required length for input such as text input. We can use its selector minlength with formControlName, formControl and ngModel in HTML template. Validators.minLength can be passed in FormControl while creating FormGroup. Here we will provide sample code for min length validation with template-driven form as well as reactive form.
1. Using Template-driven form

In text input we need to use minlength attribute.
<input name="userName" [ngModel]="user.userName" minlength="5" #uname="ngModel"> 
In the above code snippet, minlength has been assigned with the value 5. It means the value entered in text input must be of 5 characters minimum. To display validation error message, we can write code as below.
<div *ngIf="uname.errors?.minlength">
     Name must be at least 5 characters long.
</div> 
2. Using Reactive form

In reactive form we need to use Validators.minLength with FormControl while creating FormGroup.
userName: new FormControl('', Validators.minLength(5)) 
We will write code in HTML template as following.
<input formControlName="userName"> 
To display validation error message, we need to writer a getter method as given below.
get userName() {
    return this.userForm.get('userName');
} 
Now display validation error message as following.
<div *ngIf="userName.errors?.minlength">
     Name must be at least 5 characters long.
</div> 
To validate minimum length in reactive form we can also use minlength attribute with formControlName as following.
<input formControlName="userName" minlength="5"> 

maxlength Validation

Angular provides MaxLengthValidator directive for max length validation. We can use its selector maxlength with formControlName, formControl and ngModel in HTML template. Validators.maxLength can be passed in FormControl while creating FormGroup. Here we will provide code snippet for max length validation using template-driven form as well as reactive form.
1. Using Template-driven form

We need to use maxlength attribute in input text for max length validation.
<input name="userName" [ngModel]="user.userName" maxlength="10" #uname="ngModel"> 
When user starts entering value, only the max 10 characters can be entered.
2. Using Reactive form

We need to pass Validators.maxLength in FormControl while creating FormGroup.
userName: new FormControl('', Validators.maxLength(10)) 
We will write code in HTML template as following.
<input formControlName="userName"> 
Max length validation error message can be displayed as following.
<div *ngIf="userName.errors?.maxlength"> 
     Name can be max 10 characters long.
</div> 
We can also use maxlength attribute with formControlName.
<input formControlName="userName" maxlength="10"> 

Example-1: minlength and maxlength Validation using Template-driven Form

user.ts
export class User {
    userName: string;
    city: string;
} 
user-service.ts
import { Injectable } from '@angular/core';
import { User } from './user';

@Injectable()
export class UserService {
   createUser(user: User) {
       console.log('User Name: ' + user.userName);
       console.log('City: ' + user.city);
   }
} 
template-driven-form.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

import { UserService } from './user-service';
import { User } from './user';

@Component({
   selector: 'app-template',
   templateUrl: './template-driven-form.component.html'
})
export class TemplateDrivenFormComponent implements OnInit {
  isValidFormSubmitted = false;
  user = new User();
  constructor(private userService: UserService) {
  }
  ngOnInit() {
  }
  onFormSubmit(form: NgForm) {
     this.isValidFormSubmitted = false;
     if (form.invalid) {
        return;
     }
     this.isValidFormSubmitted = true;
     this.user = form.value;
     this.userService.createUser(this.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" minlength="5" maxlength="10" #uname="ngModel">
	       <div *ngIf="uname.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> 
	          <div *ngIf="uname.errors.minlength">
		     Name must be at least 5 characters long.
		  </div>
	       </div>		
	   </td>
	 </tr> 
	 <tr> 
	   <td>City:</td>
	   <td> 
	       <input name="city" [ngModel]="user.city" required minlength="3" maxlength="8" #city="ngModel">
	       <div *ngIf="city.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> 
		    <div *ngIf="city.errors.required">
			  City required. 
	            </div>
	            <div *ngIf="city.errors.minlength"> 
			  City must be at least 3 characters long.
		    </div>	
	       </div>
	   </td>
	 </tr> 	 
	 <tr> 	  
	   <td colspan="2">
	      <button>Submit</button>
	   </td>
	 </tr>	   
  </table>  
</form> 

Example-2: minlength and maxlength Validation using Reactive Form

reactive-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { UserService } from './user-service';
import { User } from './user';

@Component({
   selector: 'app-reactive',
   templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {
  isValidFormSubmitted = null;
  userForm = new FormGroup({
     userName: new FormControl('', [Validators.minLength(5), Validators.maxLength(10)]),
     city: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(8)])	 
  });
  user = new User();
  constructor(private userService: UserService) {
  }
  ngOnInit() {
  }
  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 city() {
     return this.userForm.get('city');
  }  
} 
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 && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> 
		        <div *ngIf="userName.errors.minlength">
			     Name must be at least 5 characters long.
			</div> 
			<div *ngIf="userName.errors.maxlength"> 
			     Name can be max 10 characters long.
		        </div>	
		   </div>	
	   </td>
	 </tr> 
	 <tr> 
	   <td>City: </td>
	   <td> 
	           <input formControlName="city">
		   <div *ngIf="city.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> 
		       <div *ngIf="city.errors.required"> 
			       City required. 
		       </div>			  
		       <div *ngIf="city.errors.minlength"> 
			       City must be at least 3 characters long.
		       </div>	
		       <div *ngIf="city.errors.maxlength"> 
			       City can be max 8 characters long.
		       </div>	
		   </div>
	   </td>
	 </tr> 	 
	 <tr> 	  
	   <td colspan="2">
	      <button>Submit</button>
	   </td>
	 </tr>	   
  </table>  
</form> 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		<app-template></app-template>
		<app-reactive></app-reactive>
             `
})
export class AppComponent {
} 
styles.css
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}
.error {
    color: red;
}
.success {
    color: green;
} 
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 './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
When we click on submit button, we will get following output.
Angular 2/4 minlength and maxlength Validation Example

References

MinLengthValidator
MaxLengthValidator
Form Validation

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us