Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

Angular
Home›Angular›Implement Validations in Angular 5 App

Implement Validations in Angular 5 App

By SibeeshVenu
December 2, 2017
3883
0
Share:
Get the form values

[toc]

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 to 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 how to do 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

import { FormsModule, ReactiveFormsModule } from '@angular/forms'
@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent,
    HomeComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    FormsModule, ReactiveFormsModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

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.

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

Let’s inject the FormBuilder in our constructor.

constructor(private fb: FormBuilder) {}

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

form;
  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }

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

firstName: ['Sibeesh', Validators.required]

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

<mat-card>
 <form [formGroup]="form">
 <mat-input-container>
 <input matInput placeholder="First Name" formControlName="firstName" />
 </mat-input-container>
 <mat-input-container>
 <input matInput placeholder="Last Name" formControlName="lastName" />
 </mat-input-container>
 <mat-input-container>
 <input matInput type="email" placeholder="Email" formControlName="email" />
 </mat-input-container>
 <mat-input-container>
 <input matInput type="password" placeholder="Password" formControlName="password" />
 </mat-input-container>
 <mat-input-container>
 <input matInput type="password" placeholder="Confirm Password" formControlName="confirmPassword" />
 </mat-input-container>
 <button mat-raised-button color="primary">Register</button>
 </form>
</mat-card>

Here formControlName is the tag which connects our model value and the control, so if you are not providing this value in 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, so the remaining fields are showing 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.

constructor(private fb: FormBuilder, private auth: AuthService) {
    this.form = fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', [Validators.required, isEmailValid('email')]],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }

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

function isEmailValid(control) {
  return control => {
    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,}))$/
    return regex.test(control.value) ? null : { invalidEmail: true };
  }
}

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 to 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.

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

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 can do some database actions, be ready.

Conclusion

Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share 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.

Kindest Regards
Sibeesh Venu

TagsAngularAngular 5Angular 5 ValidationsAngular ValidationsSimple Angular ValidationTwo way binding in Angular
Previous Article

Generating Your First Components And Modules in ...

Next Article

Using MongoDB on Node JS Application Using ...

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • AngularHow to

    Validation Using Template Driven Forms in Angular 5

    April 22, 2018
    By SibeeshVenu
  • Angular Virtual Scrolling Demo Middle
    Angular

    Angular Virtual Scrolling – ngVirtualScrolling

    October 24, 2018
    By SibeeshVenu
  • locaStorage in Protractor
    Angular

    End to End (E2E) Tests in Angular Application Using Protractor

    July 8, 2018
    By SibeeshVenu
  • Nav_Demo
    Angular

    Generating Your First Components And Modules in Angular 5 App

    November 16, 2017
    By SibeeshVenu
  • Azure

    Deploy Angular App Using Azure DevOps Build and Release Pipelines

    January 7, 2019
    By SibeeshVenu
  • AngularHow to

    Implement Shared Custom Validator Directive in Angular

    April 22, 2018
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version