Angular is an open-source JavaScript framework primarily used to develop single-page applications. It is a component-based framework that allows us to divide the application's functionalities into small, independent, and reusable components.
Angular provides extensive support for integrating forms in the application. There are two forms that Angular supports,
Angular reactive forms allow the handling of complex forms reactively and flexibly. Reactive forms allow to define validations and form structure in the component file (.component.ts
).
To see the application of input validation in reactive forms, let us create a simple form in our app-component.html
file.
We create the form in the code widget below. The form uses Bootstrap, which we include in the app-component.css
file:
<form> <div class="form-group"> <label for="userEmail">Email address</label> <input type="email" class="form-control" id="userEmail" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">You're password will not be shared with any 3rd party app</small> </div> <div class="form-group"> <label for="userPassword">Password</label> <input type="password" class="form-control" id="userPassword" placeholder="Password"> </div> <button type="submit" class="btn btn-primary" style="margin-left:45 %">Submit</button> </form>
Let's see the explanation of the code:
Line 1: We use the form
tag
Line 4: We create an input
field of type email
to get an email from the user.
Line 9: We create an input
field with type password
to get the password from the user.
Line 15: We create a button to submit the form.
ReactiveFormsModule
To make the form reactive, we import ReactiveFormsModule
from @angular/forms
in the app.module.ts
file. The app.module.ts
file is the root module for the Angular application. It makes the defined services, components, and other modules accessible throughout the application. The code for the app.module.ts
file is given below:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], declarations: [ AppComponent, ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { }
Line 4: We import ReactiveFormsModule
from @angular/forms
.
Line 9: We include the ReactiveFormsModule
in the imports
array to use the module functionalities.
Now, we will dive into the actual implementation of defining the form's validation rules. For that, let's have a look at the code for the app.component.ts
file below:
import { Component } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { reactiveForm:FormGroup | any; ngOnInit(): void { this.reactiveForm = new FormGroup({ emailValidator: new FormControl("", [ Validators.required, Validators.minLength(4), Validators.email, ]), passwordValidator: new FormControl("", [ Validators.required, Validators.minLength(8), ]), }); } get emailValidator() { return this.reactiveForm.get('emailValidator'); } get passwordValidator() { return this.reactiveForm.get('passwordValidator'); } submit(event: Event){ event.preventDefault() if (this.reactiveForm.valid == true){ alert("Form Submitted Successfully") } else{ alert("Ooops! fill in the fields carefully") } } }
Line 2: We import FormControl
, FormGroup
, and Validators
from the @angular/forms
module. FormControl
is used to control an individual field of the form. FormGroup
is used to manage a group of FormControls
. Validators
are used to implement pre-defined validations to the input fields.
Line 11: We create an instance of FormGroup
that contains the form controls.
Lines 12–16: We define an instance of FormControl
with the variable name emailValidator
. Form control consists of two arguments:
The first argument is the default value for the input field it will bind with.
The second argument consists of an array of validation rules. These rules can be defined using Validators
or customized validators. The validators used in the example are:
required
: Tells that the field requires some value in the form.
minLength(4)
: Specifies that the input field should contain at least 4 characters.
email
: Specifies that the input field's value must be in the email format.
Lines 17–20: We define another instance of FormControl
with the name passwordValidator
.
Lines 25–27: We create get
methods to receive emailValidator
and passwordValidator
from the FormGroup
with ease.
Lines 29–37: We create the submit
function that takes event
as a parameter. The event.preventDefault()
function prevents the form from reloading on form submission. On line 31, we check if the form is valid and display a pop-up with the message, Form Submitted Successfully
otherwise, if the form is not valid, we display Ooops! fill in the fields carefully
.
Up till now, we have defined the validation rules that are required for our input fields. Further, we will see how to integrate these validations and display error messages in the app.component.html
file.
Below, we can see the updated code for app.component.html
. Please click the "Run" button to see validations in the reactive form:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], declarations: [ AppComponent, ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { }
Line 1: We bind the reactiveForm
variable and submit
function defined in the app.component.ts
file to the form
tag and ngSubmit
directive respectively. The submit
function executes when the submit button is clicked.
Note: Binding helps us integrate validation rules defined in the
FormGroup
with the input fields.
Line 5: We define the formControlName
directive to bind the input to the emailValidator
FormControl
defined in the FormGroup
.
Lines 10–17: We define the error messages that display if the emailValidator
FormControl
is not validated.
Line 10: We define a div
with the ngIf
directive that checks if emailValidator
FormControl
rules are invalid, and the emailValidator
FormControl
is dirty or touched.
Note:
emailValidator.dirty
is true if the form control's value has changed, whereasemailValidator.touched
is true when the user focuses out theFormControl
.
Line 11: If the condition in line 10 is true, then we check if no value exists in the emailValidator
form control and display the error message Email is required
on the screen.
Line 14: Similarly, if the condition in line 10 is true, then we check if the emailValidator
form control's value does not follow the email format and display Invalid email format
on the form.
Line 22: We define the formControlName
directive to bind the input to the passwordValidator
FormControl
defined in the FormGroup
.
Lines 27–36: We define the error messages that will display if the passwordValidator
FormControl
is not validated.
Line 27: We define a div with the ngIf
directive that checks the condition if passwordValidator
FormControl
rules are not validated, and the passwordValidator
FormControl
is dirty or touched.
Line 29: If the condition at line 27 is true, then we check if no value exists in the passwordValidator
form control and display the error message Password is required
on the screen.
Line 32: We check if the passwordValidator
form control's value contains less than 8 characters and display Password should contain atleast 8 characters
on the form.
In conclusion, Angular enables us to validate its reactive forms. By following the above guidelines, we can easily integrate validations in our forms and display error messages to our users.
Free Resources