Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Min Length and Max Length Validation in Angular 12 13

Min Length and Max Length Validation in Angular 12 / 13 ?

Aman Jain, March 21, 2022March 21, 2022

Angular provides built-in library for validation, in the same way it gives validation methods to validate the string and numbers length as well. so in this tutorial i am going to explain how to use min length and max length validation in angular.

In angular validation library it provides different methods to validate the length of string and numbers. For number we use validators.min method for min length and validators.max method for max length of number.

For string we use validators.minLength and validators.maxLength methods to validate the number of char in a string.

Also read about Password and confirm password validation in angular 12 / 13 ? and How to generate component in angular cli?

Let’s start the Min Length and Max Length Validation in Angular with simple steps.

Step 1 : Create project and setup components

First step is to create the project and then create our first component so that we can create a form. I assume you have already installed node and angular

ng new project_name

Step 2 : Add form to component and import validation library

We are using FormGroup and FormControl to declare the reactive form in angular. Validators library to validate the fields. As you can see in below code we have imported FormControl, FormGroup, Validators from ‘@angular/forms’.

In next line we have created a FormGroup and assigned the controls to it.

src/app/app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

// import custom validator  class
import { CustomValidators } from './providers/CustomValidators';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
  success = '';
  registerForm = new FormGroup({
    firstName: new FormControl('', [
      Validators.required,
      Validators.maxLength(4),
    ]),
    lastName: new FormControl('', [Validators.required]),
    family_members: new FormControl('', [
      Validators.required,
      Validators.min(2),
    ]),
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [
      Validators.required,
      Validators.minLength(8),
    ]),
  });

  submitted = false;

  constructor() {}

  ngOnInit() {}

  // convenience getter for easy access to form fields
  get f() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.registerForm.invalid) {
      return;
    }

    this.success = JSON.stringify(this.registerForm.value);
  }
}

Here we used min and max to validate the numbers and minLength and maxLength to validate strings.

Step 3 : Create html file and bind FormGroup to form

Now, we are ready to bind our FormGroup to html form and FormControl to the fields.

<!-- main app container -->
<div class="readersack">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">
        <h3>Angular 12 - Reactive Forms Validation and Min and max length</h3>
        {{ success ? 'Success - ' + success : '' }}
        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label>First Name</label>
            <input
              type="text"
              formControlName="firstName"
              class="form-control"
              [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }"
            />
            <div
              *ngIf="submitted && f.firstName.errors"
              class="invalid-feedback"
            >
              <div *ngIf="f.firstName.errors.required">
                First Name is required
              </div>
              <div *ngIf="f.firstName.errors.maxlength">
                First Name should be less than 5 char.
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>Last Name</label>
            <input
              type="text"
              formControlName="lastName"
              class="form-control"
              [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }"
            />
            <div
              *ngIf="submitted && f.lastName.errors"
              class="invalid-feedback"
            >
              <div *ngIf="f.lastName.errors.required">
                Last Name is required
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>Family members in the house</label>
            <input
              type="text"
              formControlName="family_members"
              class="form-control"
              [ngClass]="{ 'is-invalid': submitted && f.family_members.errors }"
            />
            <div
              *ngIf="submitted && f.family_members.errors"
              class="invalid-feedback"
            >
              <div *ngIf="f.family_members.errors.required">
                Family member is required
              </div>
              <div *ngIf="f.family_members.errors.min">
                Family member count should be greater then 1
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>Email</label>
            <input
              type="text"
              formControlName="email"
              class="form-control"
              [ngClass]="{ 'is-invalid': submitted && f.email.errors }"
            />
            <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
              <div *ngIf="f.email.errors.required">Email is required</div>
              <div *ngIf="f.email.errors.email">
                Email must be a valid email address
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>Password</label>
            <input
              type="password"
              formControlName="password"
              class="form-control"
              [ngClass]="{ 'is-invalid': submitted && f.password.errors }"
            />
            <div
              *ngIf="submitted && f.password.errors"
              class="invalid-feedback"
            >
              <div *ngIf="f.password.errors.required">Password is required</div>
              <div *ngIf="f.password.errors.minlength">
                Password must be at least 6 characters
              </div>
            </div>
          </div>

          <div class="form-group">
            <button class="btn btn-primary">Register</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- credits -->
<div class="text-center">
  <p>
    <a href="#" target="_top"
      >Angular 12 - Reactive Forms Validation and Min and max length</a
    >
  </p>
  <p>
    <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
  </p>
</div>


Live Code and download

Related

Javascript Angular angularmaxminvalidation

Post navigation

Previous post
Next post

Related Posts

Javascript Set focus on input angular example

Set focus on input angular example

September 25, 2022March 16, 2024

Angular is a great framework for building front-end web applications. One of its many features is the ability to set focus on input angular element. This can be useful in a variety of situations, such as when you want to focus on a particular input field after a user clicks…

Read More
Javascript Laravel Multi Select Tag Autocomplete Using Select2

Laravel Multi Select Tag Autocomplete Using Select2

July 19, 2022July 19, 2022

In this article we will learn to use Laravel Multi Select Tag Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. In this article we will cover multiple…

Read More
Javascript How to create global variable in angular ?

How to create global variables in angular ?

October 3, 2022March 16, 2024

In this article, we will learn about the create global variables in Angular and how to use them. We will also see how to use them across the application by importing the file. There are different ways to create global variables in angular. One way is to use the global…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version