<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Angular 5 Validations &#8211; Sibeesh Passion</title>
	<atom:link href="https://www.sibeeshpassion.com/tag/angular-5-validations/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Tue, 10 Jul 2018 07:39:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Angular 5 Validations &#8211; Sibeesh Passion</title>
	<link>https://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Validation Using Template Driven Forms in Angular 5</title>
		<link>https://www.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/</link>
					<comments>https://www.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:58:46 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[ng5]]></category>
		<category><![CDATA[Template Driven Forms]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12798</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to do validation using template driven forms in Angular 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using Template Driven Forms. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to do validation using template driven forms in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using <em>Template Driven Forms.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. We are going to see Template Driven Forms approach here.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Install Bootstrap</h3>
<p>Before we begin, let&#8217;s install bootstrap in our application.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\My Projects\ng5&gt; npm install bootstrap --save</pre>
<p>As we are developing this application using Angular CLI, we can add the reference of Bootstrap in our Angular-CLI.json file. The styles section of that file will look like below after you add the reference.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ]</pre>
<p>Please be noted that there are many other ways to configure Bootstrap in our application, here we are not going to explain that.</p>
<h3>Importing ngForm to a variable</h3>
<p>Let&#8217;s clean codes in our Registration component and add a new form which has a form variable, and this form variable can hold the values of our form. There are many things you can do with this variable, for now, let&#8217;s say it is our model values container.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container"&gt;
  &lt;div class="row"&gt;
    &lt;div class="no-float center-block col-lg-4 col-sm-4"&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {
  }
}


</pre>
<h3>Implement Validation for User Name field using Template Driven Forms</h3>
<p>As we have created our form, now it is time to generate out input controls into it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
    &lt;div class="signup-fields"&gt;
        &lt;div class="form-group"&gt;
            &lt;input type="text" required name="userName" class="form-control" placeholder="User Name"&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;button class="btn btn-primary btn-block" type="submit"&gt;Signup&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt;</pre>
<p>What we have above is a simple HTML with template driven form, where we are going to introduce the validation. Let&#8217;s modify the userName field now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>What we are trying to achieve by the above code is, creating a reference variable userName and assign the input value to it. Basically, this is a two-way binding, where we can set the data from our component and update it in the form, and vice versa. Now if you run your application, you should see an error as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">Uncaught Error: Cannot assign to a reference or variable!
    at _AstToIrVisitor.visitPropertyWrite (compiler.js:26025)
    at PropertyWrite.visit (compiler.js:4585)
    at convertActionBinding (compiler.js:25475)
    at eval (compiler.js:27987)
    at Array.forEach (&lt;anonymous&gt;)
    at ViewBuilder._createElementHandleEventFn (compiler.js:27983)
    at nodes.(anonymous function) (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:27620:27)
    at eval (compiler.js:27928)
    at Array.map (&lt;anonymous&gt;)
    at ViewBuilder._createNodeExpressions (compiler.js:27927)</pre>
<p>This is because we are using the same name for both model and reference variable. So we should change it. To do so, let&#8217;s create a User Model (user.model.ts) and reference it to our Register component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class User {
    id: any;
    userName: string;
    email: string;
    userRole: string;
    profileImage: string;
    phoneNumber: string;
    firstName: string;
    lastName: string;
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { User } from '../models/user.model'</pre>
<p>Now we can change our input as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>Please make sure that to declare a user in registration component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }
}
</pre>
<p>Now if you run your application, you can see that the Submit button will be enabled only if the form is valid, that is, only if you enter any values in the username field.</p>
<h3>Decorate the validation message</h3>
<p>Now we know that our form is working fine, but don&#8217;t we need to give a message to the users if they haven&#8217;t given any values in the fields? Let&#8217;s add few more markups in our HTML.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>We are enabling the class &#8220;has-error&#8221; and &#8220;has-success&#8221; dynamically by checking the valid and invalid property of userName field. We are also showing our required field message in a new span if there are any required errors in our userName model. Now if you run your app, you can see that the validation is working fine.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg"><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-12799" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg" alt="" width="455" height="299" srcset="/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg 455w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-300x197.jpg 300w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-400x263.jpg 400w" sizes="(max-width: 455px) 100vw, 455px" /></a></p>
<p>But isn&#8217;t that validation showing by default, we should show the message only if the user touched our field, and refused to type anything right? Let&#8217;s add &#8220;userName.touched&#8221; in our markup.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<h3>Implement the validation for other fields as well</h3>
<p>Now it is time to implement the same in other fields.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container" style="margin-top:100px;"&gt;
  &lt;div class="row justify-content-center align-items-center"&gt;
    &lt;div class="col-lg-4 col-sm-4 center-block "&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(user)"&gt;
            &lt;div class="signup-fields"&gt;
              &lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
                &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
                &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="email.invalid &amp;&amp; email.touched" [class.has-success]="email.valid"&gt;
                &lt;input type="text" required [email]="user.email !== ''" [(ngModel)]="user.email" name="email" class="form-control" placeholder="Email"
                  #email="ngModel"&gt;
                &lt;span class="help-block" *ngIf="email.errors?.required &amp;&amp; email.touched"&gt;
                  Email is required
                &lt;/span&gt;
                &lt;span class="help-block" *ngIf="email.errors?.email &amp;&amp; email.touched"&gt;
                  Email is invalid
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="password.invalid &amp;&amp; password.touched" [class.has-success]="password.valid"&gt;
                &lt;input type="password" [(ngModel)]="user.password" required class="form-control" name="password" placeholder="Password" #password="ngModel"&gt;
                &lt;span class="help-block" *ngIf="password.invalid &amp;&amp; password.touched"&gt;
                  Password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
                &lt;input type="password" required class="form-control" name="confirmPassword" placeholder="Confirm Password" [(ngModel)]="confirmPassword"
                  #confirmPasswordControl="ngModel"&gt;
                &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div&gt;
                &lt;button class="btn btn-primary btn-block" type="submit" [disabled]="regsiterForm.invalid"&gt;Signup&lt;/button&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>For email validation, we have given an additional attribute and set the condition as [email]=&#8221;user.email !== &#8221;&#8221;, this is for not showing both the required validation and email validation together. This will show the required message if the user touched the field and not giving any values, and the email validation will get fired only if the entered value is not a valid email. Sounds good?</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg"><img decoding="async" class="alignnone size-full wp-image-12800" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg" alt="" width="476" height="601" srcset="/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg 283w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-238x300.jpg 238w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-400x505.jpg 400w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-475x600.jpg 475w" sizes="(max-width: 476px) 100vw, 476px" /></a></p>
<h3>Add register function</h3>
<p>Finally, let&#8217;s add our function register.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";
import { User } from '../models/user.model';
@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }

  register(user: User): void{
    console.log(user);
  }
}


</pre>
<p>Once it is done, let&#8217;s open our browser console and see the data.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg"><img decoding="async" class="alignnone size-full wp-image-12801" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg" alt="" width="415" height="245" srcset="/wp-content/uploads/2018/04/Console-output.jpg 415w, /wp-content/uploads/2018/04/Console-output-300x177.jpg 300w, /wp-content/uploads/2018/04/Console-output-400x236.jpg 400w" sizes="(max-width: 415px) 100vw, 415px" /></a></p>
<p>Here we have seen how we can implement validation using template driven form. I will write my next article about implementing custom validators using directives in Angular, for comparing our password and confirm password field. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>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.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Shared Custom Validator Directive in Angular</title>
		<link>https://www.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/</link>
					<comments>https://www.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:21:33 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[Angular directives]]></category>
		<category><![CDATA[Angular Shared Directive]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12804</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to create a custom validator directive in Angular 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to create a custom validator directive in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements<em>.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
<li>Validation Using Template Driven Forms in Angular 5</li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. If we create a custom shared directive for creating a compare validator, it would be a great piece of code right, which can be reused.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Creating a custom directive</h3>
<p>Let&#8217;s just create a new directive in a shared folder and name it <em>equal.validator.directive.ts. </em>Now open that file and start writing the code. Let&#8217;s import some of the core components first.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";</pre>
<p>Now Let&#8217;s define our class and @Directive.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";

@Directive({
    selector: "[appEqualValidator]",
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: EqualValidatorDirective,
        multi: true
    }]
})
export class EqualValidatorDirective implements Validator {
    validate(c: AbstractControl): { [key: string]: any; } {
        throw new Error("Method not implemented.");
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>As you can see that, we are actually inheriting our new class  EqualValidatorDirective from Validator. Now we need to change the implementations of the method inside it. We should also add our new directive in app.module.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { EqualValidatorDirective } from './shared/equal.validator.directive';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { NavComponent } from './nav/nav.component';
import { RegistrationComponent } from './registration/registration.component';
import { LoginComponent } from './login/login.component';

import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent,
    EqualValidatorDirective
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>&nbsp;</p>
<h3>Implement validate</h3>
<p>Before we do that, we should add our new cutom directive selector in our confirm password field, because that&#8217;s where we are going to use our validator. So we are going to change our markup for confirm password field as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are using the selector  <em>appEqualValidator=&#8221;password&#8221; </em>in our confirm password field. Please do check my previous posts if you are not sure how to implement other validations like email and required.</p>
<p>Now let&#8217;s go back to our custom directive and make some changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">export class EqualValidatorDirective implements Validator {
    @Input() appEqualValidator: string;
    validate(c: AbstractControl): { [key: string]: any; } {
        const controlToCompare = c.parent.get(this.appEqualValidator)
        if (controlToCompare &amp;&amp; controlToCompare.value == c.value)return { "equal": true };
        return { "notEqual": true }
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>Here, we get our confirmPassword control in the absolute control &#8220;c&#8221;, and in the next line, we are just finding our password control by getting the parent element of confirmPassword. Once we get that, we can easily perform the comparison easily right? So, if it matches we return  { &#8220;equal&#8221;: true }; or else { &#8220;notEqual&#8221;: true }. Sounds good?</p>
<h3>Introduce new span for custom message</h3>
<p>Now we have a custom validator which compares two values, and the only thing which pending is, that to create a span for showing our new message in UI. Let&#8217;s change our markup now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.notEqual 
                      &amp;&amp; confirmPasswordControl.touched &amp;&amp; !confirmPasswordControl.errors?.required"&gt;
                  Password doesn't match
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are showing the custom message only if the directive returns notEqual property and there are no required errors. Let&#8217;s run our application and see it in action.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg"><img decoding="async" class="alignnone size-full wp-image-12805" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg" alt="" width="384" height="529" srcset="/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg 259w, /wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive-218x300.jpg 218w" sizes="(max-width: 384px) 100vw, 384px" /></a></p>
<p>&nbsp;</p>
<p>Here we have seen how we can implement shared custom validator directive. Let&#8217;s connect to a database and save these values in next article. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>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.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Validations in Angular 5 App</title>
		<link>https://www.sibeeshpassion.com/implement-validations-in-angular-5-app/</link>
					<comments>https://www.sibeeshpassion.com/implement-validations-in-angular-5-app/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 02 Dec 2017 19:50:08 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[Angular Validations]]></category>
		<category><![CDATA[Simple Angular Validation]]></category>
		<category><![CDATA[Two way binding in Angular]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12559</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;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  <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 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.</p>
<h3><em>Developing an Angular 5 App</em> series</h3>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h3>Background</h3>
<p>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?</p>
<h3>Validation in Angular</h3>
<p>To get started with the Angular forms, we need to import some modules to our app.module.ts</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { FormsModule, ReactiveFormsModule } from '@angular/forms'</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent,
    HomeComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    FormsModule, ReactiveFormsModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<p>In our previous post, we have developed an Angular form in the component named Registration. Now let us open <em>registration.component.ts </em>file and import FormBuilder, Validators in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">import { FormBuilder, Validators } from '@angular/forms';</pre>
<p>Let&#8217;s inject the FormBuilder in our constructor.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">constructor(private fb: FormBuilder) {}</pre>
<p>Next, is building a form group, so that we can include our model in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">form;
  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }</pre>
<p>In the group model, the first argument is the initial value that you may need to show. You can always do as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">firstName: ['Sibeesh', Validators.required]</pre>
<p>We will have to do some more changes in our registration.component.html.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-card&gt;
 &lt;form [formGroup]="form"&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput placeholder="First Name" formControlName="firstName" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput placeholder="Last Name" formControlName="lastName" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="email" placeholder="Email" formControlName="email" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="password" placeholder="Password" formControlName="password" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="password" placeholder="Confirm Password" formControlName="confirmPassword" /&gt;
 &lt;/mat-input-container&gt;
 &lt;button mat-raised-button color="primary"&gt;Register&lt;/button&gt;
 &lt;/form&gt;
&lt;/mat-card&gt;
</pre>
<p>Here <em>formControlName </em>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.</p>
<div id="attachment_12561" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_Form_With_Validation-e1510909875736.png"><img decoding="async" aria-describedby="caption-attachment-12561" class="size-full wp-image-12561" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_Form_With_Validation-e1510909875736.png" alt="Angular_Form_With_Validation" width="634" height="309" /></a><p id="caption-attachment-12561" class="wp-caption-text">Angular_Form_With_Validation</p></div>
<p>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.</p>
<p>You can always apply some custom validations too, like Email field validators. Let&#8217;s do that now.  Please change your constructor as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">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]
    });
  }</pre>
<p>Now as you guessed, we need to implement the function <strong>isEmailValid</strong>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function isEmailValid(control) {
  return control =&gt; {
    var regex = /^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\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 };
  }
}</pre>
<p>Now that we have done our custom validation, let&#8217;s check it out in our application.</p>
<div id="attachment_12584" style="width: 624px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png"><img decoding="async" aria-describedby="caption-attachment-12584" class="size-full wp-image-12584" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png" alt="Custom Email Field Validator in Angular 5 App" width="614" height="537" srcset="/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png 408w, /wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App-300x262.png 300w, /wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App-400x350.png 400w" sizes="(max-width: 614px) 100vw, 614px" /></a><p id="caption-attachment-12584" class="wp-caption-text">Custom Email Field Validator in Angular 5 App</p></div>
<p>Let&#8217;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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;button mat-raised-button (click)="register()" color="primary"&gt;Register&lt;/button&gt;</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js"> register() {
    console.log(this.form.value);
}</pre>
<p>Please make sure that you are getting the values in your browser console.</p>
<div id="attachment_12585" style="width: 362px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Get-the-form-values-e1512243815962.png"><img decoding="async" aria-describedby="caption-attachment-12585" class="size-full wp-image-12585" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Get-the-form-values-e1512243815962.png" alt="Get the form values" width="352" height="357" /></a><p id="caption-attachment-12585" class="wp-caption-text">Get the form values</p></div>
<p><em> </em></p>
<p>That&#8217;s all for today. In our next article, we can do some database actions, be ready.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>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.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/implement-validations-in-angular-5-app/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
