How to show validation or error messages in reactive Angular form
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 forms
Angular provides extensive support for integrating forms in the application. There are two forms that Angular supports,
Validation in reactive forms
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.
Coding example
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
formtagLine 4: We create an
inputfield of typeemailto get an email from the user.Line 9: We create an
inputfield with typepasswordto get the password from the user.Line 15: We create a button to submit the form.
Importing 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
ReactiveFormsModulefrom@angular/forms.Line 9: We include the
ReactiveFormsModulein theimportsarray to use the module functionalities.
Implementing validations
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, andValidatorsfrom the@angular/formsmodule.FormControlis used to control an individual field of the form.FormGroupis used to manage a group ofFormControls.Validatorsare used to implement pre-defined validations to the input fields.Line 11: We create an instance of
FormGroupthat contains the form controls.Lines 12–16: We define an instance of
FormControlwith the variable nameemailValidator. 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
Validatorsor 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
FormControlwith the namepasswordValidator.Lines 25–27: We create
getmethods to receiveemailValidatorandpasswordValidatorfrom theFormGroupwith ease.Lines 29–37: We create the
submitfunction that takeseventas a parameter. Theevent.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 Successfullyotherwise, if the form is not valid, we displayOoops! fill in the fields carefully.
Integration of form validations
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 { }Code explanation
Line 1: We bind the
reactiveFormvariable andsubmitfunction defined in theapp.component.tsfile to theformtag andngSubmitdirective respectively. Thesubmitfunction executes when the submit button is clicked.
Note: Binding helps us integrate validation rules defined in the
FormGroupwith the input fields.
Line 5: We define the
formControlNamedirective to bind the input to theemailValidatorFormControldefined in theFormGroup.Lines 10–17: We define the error messages that display if the
emailValidatorFormControlis not validated.Line 10: We define a
divwith thengIfdirective that checks ifemailValidatorFormControlrules are invalid, and theemailValidatorFormControlis dirty or touched.
Note:
emailValidator.dirtyis true if the form control's value has changed, whereasemailValidator.touchedis 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
emailValidatorform control and display the error messageEmail is requiredon the screen.Line 14: Similarly, if the condition in line 10 is true, then we check if the
emailValidatorform control's value does not follow the email format and displayInvalid email formaton the form.Line 22: We define the
formControlNamedirective to bind the input to thepasswordValidatorFormControldefined in theFormGroup.Lines 27–36: We define the error messages that will display if the
passwordValidatorFormControlis not validated.Line 27: We define a div with the
ngIfdirective that checks the condition ifpasswordValidatorFormControlrules are not validated, and thepasswordValidatorFormControlis dirty or touched.Line 29: If the condition at line 27 is true, then we check if no value exists in the
passwordValidatorform control and display the error messagePassword is requiredon the screen.Line 32: We check if the
passwordValidatorform control's value contains less than 8 characters and displayPassword should contain atleast 8 characterson the form.
Conclusion
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