Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

Angular form validation with example

Aman Jain, August 30, 2021August 30, 2021

Angular has in-build form validation rules to validate the inputs and show errors in the ui with ease.

Before reading you should have knowledge of angular, installation process, components and angular FormGroup.

Steps to create a reactive form in angular

  1. Create a new or existing angular project, you can also read this article to create new angular project.
  2. Create a component with ng generate command.

    ng generate component helloworld

    ng generate component
  3. Import ReactiveFormsModule module add it in to import block.
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloworldComponent } from './helloworld/helloworld.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloworldComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4. Edit helloworld.component.ts and import FormGroup and FromControl from @angular/form
also add the Validators library

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

@Component({
  selector: 'app-helloworld',
  templateUrl: './helloworld.component.html',
  styleUrls: ['./helloworld.component.css']
})
export class HelloworldComponent implements OnInit {

  form: FormGroup = new FormGroup(
      {
        name:new FormControl("inital value ",[Validators.required,Validators.minLength(4)]),
        email:new FormControl("inital value ",[Validators.required]),
        password:new FormControl("",[Validators.required]),
        
      }
    );
  constructor() { }

  ngOnInit(): void {

     
  }

  submitForm(){
    if(this.form.valid){
      console.log("send request to server",this.form.value);
// send request to server

    } 
    else{
      console.log("Form has errors");
    }
  }

}

We have added the Validators.required, Validation.minLength(4) validation here, which make the input required. submitForm function to handle the submission

5. Edit HTML file, add attribute [formGroup] to form and formControlName to each input

<h1>Helloworld works!</h1>
<form [formGroup]="form" (submit)="submitForm()">
    <div>
        Name : <input type="name" formControlName="name" placeholder="Name" /> <br>

        <div *ngIf="form.controls.name.invalid && (form.controls.name.dirty || form.controls.name.touched)"
            class="alert alert-danger">

            <div *ngIf="form.controls.name.errors?.required">
                Name is required.
            </div>
            <div *ngIf="form.controls.name.errors?.minlength">
                Name must be at least 4 characters long.
            </div>

        </div>
    </div>
    <div>
        Email : <input type="email" formControlName="email" placeholder="Email" /> <br>
        <div *ngIf="form.controls.email.invalid && (form.controls.email.dirty || form.controls.email.touched)"
            class="alert alert-danger">

            <div *ngIf="form.controls.email.errors?.required">
                Email is required.
            </div>
            <div *ngIf="form.controls.email.errors?.email">
                Enter valid email
            </div>

        </div>
    </div>
    <div>
        Password : <input type="password" formControlName="password" placeholder="Password" /> <br>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>

</form>

In the above html file we have implemented states of a form control, every time form changes angular run validations and produces the errors list with VALID or INVALID state.


1. Invalid : Invalid state tells that input field has errors.
2. Dirty : If the user change the value then control marked as “dirty”.
3. Touched : If the user blurs the input then control is marked as “touched”.

errors contains the list of all errors.

Output :

  • Screenshot 2021 08 30 at 10.49.51 PM
OUTPUT OF FORM VALIDATION

Related

Javascript Angular

Post navigation

Previous post
Next post

Related Posts

Javascript How to Insert script tag dynamically in html in angular

How to Insert script tag dynamically in angular ?

March 24, 2022August 4, 2022

Sometimes we want to insert script tag in angular app, For an instance we have third party APIs or widget and we wanted to add it in our page then in this condition provided script are not angular friendly or we can say it can be pure JavaScript. so to…

Read More

How to check jQuery checkbox checked or not ?

January 25, 2022January 25, 2022

In this article i will show you multiple way to check or validate if a checkbox is checked or not. Also i will show you to check a checkbox programmatically. In the post we will learn all possibilities to validate a checkbox and how we can check a checkbox using…

Read More
Angular How to use moment js in angular

How to use moment js in angular ?

October 13, 2022March 16, 2024

This post covers how to use Moment.js in Angular. We’ll go over why Moment.js is useful, how to install it, and how to use it in Angular to manipulate dates and times. Moment.js is a powerful and flexible library for manipulating dates and times in JavaScript. It has been around…

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