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

How many type of methods in Restful api?

August 28, 2021February 22, 2024

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

Read More
Javascript How to Insert style tag dynamically in html in angular

How to Insert Style Tag Dynamically in Angular ?

August 4, 2022March 16, 2024

Sometimes we want to insert style 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 and style are not angular friendly or we can say it can be pure JavaScript…

Read More
Javascript Angular ngClass conditional class Example

Angular ngClass conditional class Example

October 8, 2022March 16, 2024

In this blog post, we’ll explore Angular ngClass conditional class Example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply classes and style to elements. We’ll discuss how to use…

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

  • July 2025
  • June 2025
  • 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

  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version