A Guide on Angular Form Validation

Read it in 10 Mins

Published
25th Nov, 2022
Views
3,281
A Guide on Angular Form Validation

AngularJS is an open-source Javascript framework that has made it easier for developers to create dynamic web applications. You can choose HTML as your template language, making your application clear. You do not have to do much coding with the data binding and dependency injection features. You can seamlessly use Angular with any server technology. AnjularJS is an extension to HTML and has made things easier that would have been done with HTML.

AngularJS is known for its ability to change static HTML to dynamic HTML. It is said to be an HTML extension due to its built-in attributes and components. Many developers use AngularJS to create dynamic apps with angular professional certification. Below are some reasons why it is preferred over another JavaScript framework. 

  • Dependency injection- components have dependencies rather than hard-coded them within components. 
  • Two-way data binding. You can use the web development course syllabus to get this in the delta. 
  • It tests every component using unit testing and end-to-end testing. 
  • It has a model view controller pattern to develop applications. 

One of the essential parts of any dynamic website is dealing with the user's dynamic data. It is mainly done using forms. With AngularJS, you can easily create forms. When working with forms, you must check if the user has provided the correct data. This can be done using form validations. Angular provides an excellent facility for validating user inputs and showing validation messages on the screen if something goes wrong during the execution of the application. It has built-in validators to make your validating work easier. 

This article will show us how to create and validate forms with a simple Angular form validation example. 

Create and Validate Forms in Angular

Forms can be simple or complex, depending on your requirement. A developer can include as many input fields as they want. Also, you can implement simple or complex validation login on single or multiple input fields. Angular comes with a form module binding the form field to the Angular component class.

This class simply tracks the changes made to the form fields to respond accordingly. The Angular forms have built-in validators that validate the inputs provided by the user. You can create your custom validator. If the validation fails, the user will get an error message. Then Angular form bundles all the input fields into an object structure after the user submits the desired form. Angular has two different approaches for creating the forms- The template-driven forms approach and another one is Reactive forms in angular

Template-driven forms approach 

It is the most straightforward approach to form creation where the logic stays in the template.

Reactive forms approach 

The form is created in the component class and then bound to the HTML elements. In this case of form creation, the logic is stored within the component as an object, making testing the component easier.

Angular Forms Fundamentals

Now, we will discuss the fundamentals of any Angular form. You must understand them before you start creating forms and validating them. The Angular Forms module consists of two Building blocks- FormControl, and FormGroup, irrespective of your form approach.

FormControl with a single input field in Angular form. For example- 

First Name : <input type="text" name="firstname" /> 

A form can have several input fields, and we need an object of the FormControl class for each field. The FormControl object stores information about that field that needs to be validated. It stores the state of the input field, such as untouched, dirty, pristine, etc. 

A FormGroup consists of the FormControl objects. In some cases, you can also have multiple FormGroups, such as separating personal and professional details sections of a user registration form. So, if you want to add validation to an Angular form, you will need two things: 

  • One FormGroup object
  • A FormControl object for each field

We can create these objects in two ways- template-driven and reactive forms.

Forms in Angular

Most of the frontend applications are form-intensive, especially for enterprise development. Such applications are a colossal form, containing multiple tabs and dialogs and with validation business logic. 

Each form-intensive application has to provide answers to the following problems: 

  • How to track the global form state. 
  • What parts of the form are valid and which are invalid. 
  • Displaying error messages to the user to know where the potential error lies and how to fix it. 

Such tasks are similar across applications and require a framework to implement the validation. The Angular framework has excellent strategies for handling forms, so let’s get started. 

But, before we start creating and validating forms, we will do some basic installation. 

  • Check if you have installed the latest Node version on your system. Run the following command. 

node –version 

  • Check the installed version of npm using the following command.

npm -v 

  • Install the latest version of Angular using the following command from your terminal. Here “-g” flag specifies that the package will be installed globally. 

npm install -g npm@8.12.2 

ng v 

  • Now create a new project, “hello_valid”. 

ng new hello_valid 

  • Go to VSCode, and open the above-created folder. 

  • Now, we will check if the primary application is running fine, so run the following command from the terminal. 

ng serve 

Now, we are ready to get started. 

Template-Driven Forms

Template-driven forms are created using directives in the template. It is used to create a simple form application. To start the template-driven forms, we must import FormsModule in app.module.ts, as shown below. 

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HeroFormComponent } from './hero-form/hero-form.component';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent,
HeroFormComponent
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Create a class using the following command. 

ng generate class Hero

Now, go to the VSCode -> app module -> hero.ts file, and add the following code. 

export class Hero {
constructor(
public id: number,
public name: string,
public power: string,
public alterEgo?: string
) { }
} 

Now, we will create a HeroForm component using the below command from the terminal. 

ng generate component HeroForm

Now, add the following code in the hero-form.component.ts file. 

import { Component } from '@angular/core';
import { Hero } from '../hero';
@Component({
selector: 'app-hero-form',
templateUrl: './hero-form.component.html',
styleUrls: ['./hero-form.component.css']
})
export class HeroFormComponent {
submitted = false;
onSubmit() { this.submitted = true; }
get diagnostic() { return JSON.stringify(this.model); }
}

Now, add the following code in the app.component.html file. 

<app-hero-form></app-hero-form>

Now, we will add the following code in the hero-form.component.html. 

<div class="container">
<h1>Hero Form</h1>
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" required>
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input type="text" class="form-control" id="alterEgo">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

Now that your basic form is ready, you can run it using the following command from the terminal. 

ng serve 

The application has been compiled successfully. We will launch the application again from the browser. 

Validation in Template-Driven Forms

Here, we are using another example to validate the email and phone numbers.

We will create a new application for validation. 

ng new tempform 

Then we will create a class using the following command. 

ng generate class adddress

Go to VSCode. Use the following code in app.module.ts. 

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { TemplateDrivenFormComponent } from './template-driven-form/template-driven-form.component'; 
@NgModule({ 
declarations: [ 
AppComponent, 
TemplateDrivenFormComponent 
], 
imports: [ 
BrowserModule, 
AppRoutingModule 
], 
providers: [], 
bootstrap: [AppComponent] 
}) 
export class AppModule { } 

Use the following code in the address.ts file. 

export interface addressModel{ 
email: string, 
phone: string, 
} 

Now create a component using the following code. 

ng generate component TemplateDrivenForm 

Use the following code for template-driven-form-component.ts file. 

import { Component, OnInit} from '@angular/core'; 
import { addressModel } from '../adddress'; 
import { NgForm } from '@angular/forms'; 
import { NgModel } from '@angular/forms'; 
@Component({ 
selector: 'app-template-driven-form', 
templateUrl: './template-driven-form.component.html', 
styleUrls: ['./template-driven-form.component.css'] 
}) 
export class TemplateDrivenFormComponent implements OnInit { 
model: addressModel = { 
email: '', 
phone: '' 
}; 
constructor() { } 
ngOnInit() { 
} 
onFormSubmit() { 
console.log("Full Address", this.model); 
} 
} 

Use the following code for template-driven-form-component.html file. 

<form class="form-horizontal" role="form" ></form> 
<div class="row"> 
<div class="col-md-4 col-md-offset-4" style="margin-top: 50px; border: 1px solid rgb(100, 98, 98); padding: 30px;"> 
<form class="form-horizontal" role="form" > 
<fieldset> 
<legend>Address Details: 
<strong>Template Driven Form</strong> 
</legend> 
//angular form validation email
<div class="form-group"> 
<label class="col-sm-2 control-label" for="textinput">Address</label> 
<div class="col-sm-10"> 
<input type="text" 
required UserRegistrationFormValidators.usernameShouldBeValid 
name="address" placeholder="Enter Address" class="form-control"> 
</div> 
</div> 
//angular form validation phone number
<div class="form-group"> 
<label class="col-sm-2 control-label" for="textinput">Phone number</label> 
<div class="col-sm-10"> 
<input type="text" 
required name="phone" placeholder="Enter Phone Number" class="form-control"> 
</div> 
</div>
//angular form validation on submit
<div class="form-group"> 
<div class="col-sm-offset-2 col-sm-10"> 
<div class="pull-right"> 
<button type="submit" class="btn btn-primary" style="margin: 4px;">Save</button> 
<button type="reset" class="btn btn-default">Submit</button> 
</div> 
</div> 
</div> 
</fieldset> 
</form> 
</div> 
</div> 

Use the following code in app.component.html 

<app-template-driven-form></app-template-driven-form> 

Now compile the application using ng serve. 

Go to http://localhost:4200, and you will get the following application running. 

You will be asked to fill in the detail before saving the details. 

Writing a Custom Validator

Sometimes the built-in validators cannot help you validate some use-cases. In that case, you need to create a custom validator function. You can create a validator function implementing the ValidatorFn interface with the below syntax. 

interface ValidatorFn { 
(control: AbstractControl): ValidationErrors | null 
} 
The ValidationErrors must be an object with one or more key-value pairs: 
type ValidationErrors = { 
[key: string]: any; 
}; 

Where the key is of string type, you can use any value to provide more information about the validation error. We can create our custom validator anywhere in the function. For example- 

import { ValidationErrors, AbstractControl } from '@angular/forms'; 
export class RegistrationForm { 
static usernameValid(control: AbstractControl): ValidationErrors | null { 
if ((control.value as string).indexOf(' ') >= 0) { 
return { shouldNotHaveSpaces: true } 
} 
// If there is no validation failure, return null 
return null; 
} 
} 

Then we can use this validator within the email. 

<div class="form-group"> 
<label class="col-sm-2 control-label" for="textinput">Address</label> 
<div class="col-sm-10"> 
<input type="text" 
required RegistrationForm.usernameValid 
[(ngModel)]="person.address" name="address" placeholder="Enter Address" class="form-control"> 
</div> 

Reactive Forms

The process will be the same for the reactive form creation. So we only will see the code. Here, we will explicitly create a FormControl object within the component of that template. Below is the HTML form without any ngModel directive. 

<div class="form-group"> 
<label for="name">Name</label> 
<input type="text" class="form-control" id="name"> 
</div> 
<div class="form-group"> 
<label for="username">Username</label> 
<input type="text" class="form-control" id="username"> 
</div> 
We will explicitly create FormGroup and FormControls for each field in the component. 
form = new FormGroup({ 
'email': new FormControl(), 
'username': new FormControl(), 
}) 

Now, we will associate these FormControl objects to the fields in the HTML form. 

<form [formGroup]="registrationForm"> 
<div class="form-group"> 
<label for="name">Name</label> 
<input type="text" class="form-control" id="name" 
[formControlName]="name"> 
</div> 
<div class="form-group"> 
<label for="username">Username</label> 
<input type="text" class="form-control" id="username" 
[formControlName]="username"> 
</div> 
<form> 

For react forms, you need to ReactiveFormsModule in your main module app.module.ts. 

Validations in Reactive Forms

We do not use the ngModel directive and HTML5 validation attributes in reactive forms. You must specify the validators while creating the objects of the FormControl in the component. You can use the below-mentioned syntax for the FormControl class: 

class FormControl extends AbstractControl { 

constructor(formState: any = null, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]) 

// code 

If you want to add the built-in validator functions for a FormControl, you must pass it to the appropriate ValidatorFn.

For the following example, we've used the following built-in validators required, minLength, and maxLength. 

registrationForm = new FormGroup({ 
'name': new FormControl('Enter your name', [ 
Validators.required, 
Validators.minLength(10), 
Validators.maxLength(20) 
]), 
'username': new FormControl('', Validators.required), 
}) 

Now, you can go back to the template and specify the validation messages: 

<form [formGroup]="registrationForm"> 
<div class="form-group"> 
<label for="name">Name</label> 
<input type="text" class="form-control" id="name" 
[formControlName]="name"> 
<div *ngIf="registrationForm.get('name').invalid && (registrationForm.get('name').dirty || registrationForm.get('name').touched)" 
class="alert alert-danger"> 
<div *ngIf="registrationForm.get('name').errors.required"> 
Name is required. 
</div> 
<div *ngIf="registrationForm.get('name').errors.minlength"> 
Name cannot be more than 30 characters long. 
</div> 
<div *ngIf="registrationForm.get('name').errors.minlength"> 
Name must be at least 2 characters long. 
</div> 
</div> 
</div> 
<div class="form-group"> 
<label for="username">Username</label> 
<input type="text" class="form-control" id="username" 
[formControlName]="username"> 
</div> 
<form> 

Custom Validators for Reactive Forms

You can simply create the custom validator function as we did in the case of the Template-Driven form. Here, we are using the same custom validator function.

registrationForm = new FormGroup({ 
'name': new FormControl('Enter your name', [ 
Validators.required, 
Validators.minLength(2), 
Validators.maxLength(30) 
]), 
'username': new FormControl('', [ 
Validators.required, 
UserRegistrationFormValidators.usernameShouldBeValid 
]), 
}) 

Angular Forms and Validations Example

Below is a list of all built-in validators in Angular. 

  • minLength: Validator that requires the value of a minimum length. 
  • maxLength: Validator that requires a value of a maximum length. 
  • Pattern: Validator that requires a regex to its value.
  • email: performs email validation. 
<form name="myForm"> 
<input name="myInput" ng-model="myInput" type="email"> 
</form> 
<p>The input's valid state is:</p> 
<h1>{{myForm.myInput.$valid}}</h1> 
  • compose: is used to validate more than one criteria for the same form field. 
  • required: Validator that requires to have a non-empty value. 
<form name="myForm"> 
<input name="myInput" ng-model="myInput" required> 
</form> 
<p>The input's valid state is:</p> 
<h1>{{myForm.myInput.$valid}}</h1> 

Conclusion

Angular is the most preferred language when it comes to creating dynamic applications. Even you can create forms with proper validation to it. It ensures security and allows the user to fill all the fields. With Angular, you can create template-driven and reactive forms. Also, you can add validation using its in-built validations, making it easier to check if all the fields are filled by the user properly. If you are new to Angular, then you must go for KnowledgeHut’s angular professional certification. In this angular form validation tutorial, we have mentioned some simple examples to explain the concept. 

Frequently Asked Questions (FAQs)

1. What is form validation in Angular?

Forms are interactive ways to connect with the application. It allows users to provide information that needs validation for various reasons, such as security or proper data to get accurate results. In Angular, you can quickly validate your forms using the form module binding the form field to the Angular component class. This class simply tracks the changes made to the form fields to respond accordingly. The Angular forms have built-in validators that validate the inputs provided by the user.

2. How do we validate Angular?

In Angular, you can quickly validate your forms using the form module that binds the form field to the Angular component class. This class keeps track of the changes made to the form fields so it can respond instantly to the users. The Angular forms have built-in validators that validate the inputs provided by the user.

3. What is form validation?

Form validation is a process that checks whether the information provided by a user is correct or not. The form will provide an error message or alert the user so they can fix the issue asap. Once the user provides the correct information, the form will not throw any error and lets you continue with the next step.

4. How do you check if the form is valid or not?

You can simply use the following code to check the form's validity. 

form: FormGroup; 
onSubmit(){ 
//checks if form is valid 
if( this.form.valid){ 
//more code here 
} 
} 
Profile

Aashiya Mittal

Author

Aashiya has worked as a freelancer for multiple online platforms and clients across the globe. She has almost 4 years of experience in content creation and is known to deliver quality content. She is versed in SEO and relies heavily on her research capabilities.

Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)