How to trigger Form Validators in Angular2 ?
Last Updated :
28 Jul, 2020
In Angular 2, the best way to deal with complex forms is by using Reactive forms. Below we are going to elaborate on how to trigger form validators for login page.
In reactive forms, we use FormControl and by using this, we get access to sub-fields of form and their properties. Some of their properties are dirty, touched, untouched, pristine, valid, errors and etc. Using these properties, we can actually trigger validations according to the requirement.
- Dirty: This property gets activated if the user changes the value of the sub-field from the default value.
- Touched: If the user visits the subfield then the touched property value is set to "true".
- Untouched: If the user doesn't visit the subfield then untouched property value is set to "true". It is completely opposite to touched property.
- Pristine: If the user visits the sub-field and doesn't make any change in its value then it is set to "true".
- Valid: If the form fulfills all the form validations then it will be "true".
- Errors: Angular on client-side generates a list of errors that contain all the inbuilt errors like required, maxLength, pattern, minLength, etc.
Using the above-discussed properties, we can trigger the form validations with custom messages. Using the FormControl of every sub-field and checking its properties like touched, dirty and etc, we can validate the form according to the need.
Approach:
- First, add all the form controls in the component.ts file according to the .html file.
- Then add validations in component.ts file for the required subfields, Example: Required, Max Length, Pattern, etc.
- Make sure you imported everything from Validators from 'angular@/forms'
- Then add validation messages in.html file which is demonstrated in the below code.
- Also, import all the dependencies from 'angular@/material' in the module file.
For better animations and styling angular provides Angular material which has abundant information regarding the styling. Using angular material, the form is styled. Hence, we are using tags like <mat-form-field>, <mat-error>, <mat-label> and matInput.
We can import from angular material after installing it using npm. The command for importing it is mentioned below:
ng add @angular/material
Code Implementation: Below is the implementation of the above approach.
app.module.ts:
JavaScript
import { BrowserModule } from
'@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from
'@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule }
from '@angular/forms';
import { MatInputModule } from
'@angular/material/input';
import { MatDialogModule } from
'@angular/material/dialog';
import { MatFormFieldModule } from
'@angular/material/form-field';
import { MatIconModule } from
'@angular/material/icon';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MatInputModule,
MatFormFieldModule,
MatIconModule,
MatDialogModule,
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
JavaScript
import { Component, OnInit }
from '@angular/core';
// Imports
import { FormGroup, FormControl,
Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit() {
}
profile = new FormGroup(
{
// Setting Validation Controls
email: new FormControl('',
[Validators.required,
Validators.minLength(8),
Validators.pattern(
/^\w+@[a-z0-9A-Z_]+?\.[a-zA-Z]{2, 5}$/)]),
password: new FormControl('',
[Validators.required,
Validators.minLength(8),
Validators.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8, }$/)])
}
);
}
app.component.html:
HTML
<div class="container-fluid">
<div class="row">
<div class="col-12 col-sm-6
col-md-6 col-lg-12">
<h4>Login to start</h4>
<form [formGroup]="profile">
<mat-form-field appearance="outline">
<mat-label>Email</mat-label>
<input type="email" matInput
placeholder="Enter Email"
formControlName="email">
<mat-error *ngIf=
"profile.controls['email'].errors?.pattern && profile.controls['email'].touched">
Enter a valid email with
requested pattern
</mat-error>
<mat-error *ngIf=
"profile.controls['email'].errors?.minLength && profile.controls['email'].touched">
Email should have minimum
8 characters
</mat-error>
<mat-error *ngIf=
"profile.controls['email'].errors?.required && profile.controls['email'].touched">
Email is required
</mat-error>
</mat-form-field>
<mat appearance="outline">
<mat-label>Password</mat-label>
<input matInput type="password"
placeholder="Enter password"
formControlName="password">
<mat-error *ngIf=
"profile.controls['password'].errors?.required && profile.controls['password'].touched">
Password is required
</mat-error>
<mat-error *ngIf=
"profile.controls['password'].errors?.minLength && profile.controls['password'].touched">
Enter a password with
more than 8 letters
</mat-error>
<mat-error *ngIf=
"profile.controls['password'].errors?.pattern && profile.controls['password'].touched">
Enter a password with
valid pattern
</mat-error>
</mat - form - field>
<button class="btn btn-primary"
[disabled]="!profile.valid">
Submit
</button>
</form>
</div>
</div>
</div>
Output: Hence, we have successfully triggered form validations.


Similar Reads
How to validate checkbox form in angular 15
In Angular applications, it is often necessary to validate form inputs to ensure that users provide the required information correctly. Checkbox inputs are commonly used to allow users to select one or more options from a list. This article will cover different approaches to validating checkbox inpu
5 min read
How to perform custom validation in Angular forms?
Angular's built-in form controls provide a set of predefined validators for common validation such as required fields, email format, and minimum/maximum values. However, there may be cases where you need to implement custom validation logic specific to your application's requirements. Angular offers
4 min read
How To Use Reactive Forms in Angular?
In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class. Core ComponentsFormGroup: Repres
5 min read
How to Validate Data in AngularJS ?
In this article, we will know to validate the data in Angular JS, along with understanding the various ways to validate the data through the examples. AngularJS allows client-side form validation. Form validation is necessary because it ensures that the data in the form is correct, complete, and are
10 min read
Purpose of Validators class in Angular
The Validators class in Angular provides a set of built-in validation functions that can be used to validate form controls and user input. It is part of the @angular/forms module and is commonly used in conjunction with Angular's Reactive Forms or Template-driven Forms. PrerequisitesTypeScriptAngula
4 min read
Angular PrimeNG Form Slider Input
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Slider Input Component in Angular PrimeNG. The Slider Co
2 min read
How to get the value of the form in Angular ?
In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object. Syntax: form.value Return Value: object: It is an object containing form value Approach:Â Create the Angular app to be usedIn app.componen
1 min read
How to Add Form Validation In Next.js ?
Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. NeÂxt.js, a versatile framework for building ReÂact applications, offers form validation that helps verify useÂr input against predefined criteÂria, provides immediate feedback, and enhances data qual
3 min read
How to Implement Angular Forms?
Creating a Form in Angular includes the use of directives such as ngSubmit and ngModel. We will be using a functional component to render the elements. Various HTML elements are created in the project. To implement the project we will create the styling using CSS. Prerequisites:Functional Components
4 min read
AngularJS Form Validation
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not. Form input fi
3 min read