Implement Validations In Angular 5 App

Table of contents
  • Introduction
  • Developing an Angular 5 App series
  • Source Code
  • Background
  • Validation in Angular
  • Conclusion
  • Your turn. What do you think?
Introduction

This post is a continuation of the course Developing an Angular 5 App series. If you haven’t gone through the previous posts yet, I strongly recommend you do that. You can find the links to the previous posts below. In this post, we are going to implement Two Way binding and validations in Angular 5 registration form. So, at the end of this article, you will be proficient in performing validations in Angular. I hope you will like this article.

Developing an Angular 5 App series

These are the previous posts in this series. Please go ahead and have a look.

  1. What Is New and How to Set Up our First Angular 5 Application
  2. Angular 5 Basic Demo Project Overview
  3. Generating Your First Components And Modules in Angular 5 App
  4. Implement Validations in Angular 5 App

Source Code

You can always clone or download the source code here.

Background

Validations are having a vital role in all the applications. Without validation, anyone can push invalid data to your application. So here, we are also going to implement some validations, it is our application and we want to make it perfect right.

Validation in Angular

To get started with the Angular forms, we need to import some modules to our app.module.ts.

  1. import {  
  2.     FormsModule,  
  3.     ReactiveFormsModule  
  4. } from '@angular/forms'  
  5. @NgModule({  
  6.     declarations: [  
  7.         AppComponent,  
  8.         RegistrationComponent,  
  9.         HomeComponent,  
  10.         NavComponent  
  11.     ],  
  12.     imports: [  
  13.         BrowserModule,  
  14.         BrowserAnimationsModule,  
  15.         AppRoutingModule,  
  16.         MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,  
  17.         FormsModule, ReactiveFormsModule,  
  18.         RouterModule.forRoot(myRoots)  
  19.     ],  
  20.     providers: [],  
  21.     bootstrap: [AppComponent]  
  22. })  

In our previous post, we have developed an Angular form in the component named Registration. Now, let us open registration.component.ts file and import FormBuilder validators in it.

  1. import { FormBuilder, Validators } from '@angular/forms';  

Let’s inject the FormBuilder in our constructor.

  1. constructor(private fb: FormBuilder) {}  

Next is building a form group so, that we can include our model in it.

  1. form;  
  2. constructor(private fb: FormBuilder) {  
  3.     this.form = fb.group({  
  4.         firstName: ['', Validators.required],  
  5.         lastName: ['', Validators.required],  
  6.         email: ['', Validators.required],  
  7.         password: ['', Validators.required],  
  8.         confirmPassword: ['', Validators.required]  
  9.     });  
  10. }  

In the group model, the first argument is the initial value that you may need to show. You can always do as preceding.

  1. firstName: ['Sibeesh', Validators.required]  

We will have to do some more changes in our registration.component.html.

  1. <mat-card>  
  2.     <form [formGroup]="form">  
  3.         <mat-input-container> <input matInput placeholder="First Name" formControlName="firstName" /> </mat-input-container>  
  4.         <mat-input-container> <input matInput placeholder="Last Name" formControlName="lastName" /> </mat-input-container>  
  5.         <mat-input-container> <input matInput type="email" placeholder="Email" formControlName="email" /> </mat-input-container>  
  6.         <mat-input-container> <input matInput type="password" placeholder="Password" formControlName="password" /> </mat-input-container>  
  7.         <mat-input-container> <input matInput type="password" placeholder="Confirm Password" formControlName="confirmPassword" /> </mat-input-container> <button mat-raised-button color="primary">Register</button> </form>  
  8. </mat-card>  

Here, formControlName is the tag which connects our model value and the control, so if you are not providing this value to your HTML, the validation for that particular control will not work. Now, let us run our application and see the output.Angular_Form_With_Validation

Angular_Form_With_Validation

Please be noted that we have given value only for the field First Name, the remaining fields are shown in red color when we click our Register button. So, our validation is working as expected.

You can always apply some custom validations too, like Email field validators. Let’s do that now. Please change your constructor as preceding.

  1. constructor(private fb: FormBuilder, private auth: AuthService) {  
  2.     this.form = fb.group({  
  3.         firstName: ['', Validators.required],  
  4.         lastName: ['', Validators.required],  
  5.         email: ['', [Validators.required, isEmailValid('email')]],  
  6.         password: ['', Validators.required],  
  7.         confirmPassword: ['', Validators.required]  
  8.     });  
  9. }  

Now, as you guessed, we need to implement the function isEmailValid.

  1. function isEmailValid(control) {  
  2.     return control => {  
  3.         var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/  
  4.         return regex.test(control.value) ? null : {  
  5.             invalidEmail: true  
  6.         };  
  7.     }  
  8. }  

Now that we have done our custom validation, let’s check it out in our application.Custom Email Field Validator in Angular 5 App

Custom Email Field Validator in Angular 5 App

Let’s create a click event for our Register button and get the form values that we have typed so that we can pass these values to our server and save the same in our next article.

  1. <button mat-raised-button (click)="register()" color="primary">Register</button>  
  2. register() {  
  3.    console.log(this.form.value);  
  4. }  

Please make sure that you are getting the values in your browser console.

Get the form values

Get the form values

That’s all for today. In our next article, we will do some database actions, be ready.

Conclusion

Thanks a lot for reading. Did I miss anything you may think is needed? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.


Similar Articles