DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Implement Validations in Angular 5 App

Implement Validations in Angular 5 App

In this post, we are going to go through the process of implementing two-way binding and validations in an Angular 5 registration form.

Sibeesh Venu user avatar by
Sibeesh Venu
·
Dec. 26, 17 · Tutorial
Like (22)
Save
Tweet
Share
23.18K Views

Join the DZone community and get the full member experience.

Join For Free

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 an angular 5 registration form. so at the end of this article, you will know how to make 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

you can always clone or download the source code here .

background

validations play a vital role in all applications, for, without validation, anyone can push invalid data to your application. so here we are also going to implement some validations, because 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 developed an angular form in the component named registration. now let us open the registration.component.ts file and import formbuilder, with validators in it.

import { formbuilder, validators } from '@angular/forms';

let's inject the formbuilder in our constructor.

constructor(private fb: formbuilder) {}

next, we build 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 follows:

firstname: ['sibeesh', validators.required]

we will have to make 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.

image title

please note that we have given a value only to the field 'first name,' so the remaining fields become red 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 follows:

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 made our custom validation, let's check it out in our application.

image title

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 that info 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.

that's all for today. in our next article, we will perform some database actions, so be ready!

thanks a lot for reading. did i miss anything that you think is needed? did you find this post useful? i hope you liked this article. please share your valuable suggestions and feedback.

kindest regards,
sibeesh venu

AngularJS app

Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Fixing Bottlenecks in Your Microservices App Flows
  • Running Databases on Kubernetes
  • Microservices 101: Transactional Outbox and Inbox
  • How To Select Multiple Checkboxes in Selenium WebDriver Using Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: