Angular 8 Advance form validation

In this Angular 8 form validation tutorial, we will show you how to create public message for the form validation and custom validation rules. This will make easy to use and flexible.

Before get start you must have the knowledge about the validation if you don’t know, Please read the ‘Angular 8 Form Validation‘ post first.

Let’s get started

First we will create a service. In this service we will define our error messages and custom validation method.

Type the below command to create a service

ng g service validation

Replace the file with the below code

import { Injectable } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class ValidationService {

  constructor() { }

  static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {

    let config = {
        'required': 'This field is required',
        'email': 'The ' + validatorName + ' must contain a valid email address',
        'invalidPassword': 'Password must be at least 6 characters long, and contain a number.',
        'minLength': `Minimum length ${validatorValue.requiredLength}`,
        'invalidMatch': 'The password and confirm password must match'

    };

    return config[validatorName];
  }
  
  static password(control: FormControl) {
    
    // {6,100}           - Assert password is between 6 and 100 characters
    // (?=.*[0-9])       - Assert a string has at least one number
    if (control.value.match(/^(?=.*[0-9])[[email protected]#$%^&*]{6,100}$/)) {
        return null;
    } else {
        return { 'invalidPassword': true };
    }
  }

  static match(controlName: string, matchingControlName: string) {

    return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];

      if (matchingControl.errors && !matchingControl.errors.invalidMatch) {
          return;
      }

      // set error on matchingControl if validation fails
      if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ invalidMatch: true });
      } else {
          matchingControl.setErrors(null);
      }
  }
  }
}

Here under the getValidatorErrorMessage method you can define your own error messages. You may notice we have a static method called password. This is our rule for the validation.

Now we will create a new component. Type the below command to create component

ng g component errorMessage

Open the error-message.component.ts file and put the below code on it

import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ValidationService } from '../validation.service';

@Component({
  selector: 'error-message',
  templateUrl: './error-message.component.html',
  styleUrls: ['./error-message.component.css']
})
export class ErrorMessageComponent {
  @Input() control: FormControl;

  constructor() { }
  
  get errorMessage() {
    for (let propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName)) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }    
    return null;
  }
}

Then open the error.message.component.html file and put the below html

<div class="text-danger" *ngIf="errorMessage !== null">{{errorMessage}}</div>

Now register ValidationService service and ErrorMessage component for our application. So that we can use in our application. To registered open app.module.ts file and import the ValidationService service and ErrorMessage component.

import { ValidationService } from './validation.service';
import { ErrorMessageComponent } from './error-message/error-message.component';

Then add the ValidationService in the providers like the below

providers: [ ValidationService ]

Then add the ErrorMessageComponent in the declarations

declarations: [
    ..
    ErrorMessageComponent
]

After adding the validationService our app.module.ts file will looks like this

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { FormComponent } from './form/form.component';
import { RegisterComponent } from './register/register.component';
import { ErrorMessageComponent } from './error-message/error-message.component';
import { ValidationService } from './validation.service';


@NgModule({
  declarations: [
    AppComponent,
    FormComponent,
    RegisterComponent,
    ErrorMessageComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
  ],
  providers: [ ValidationService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now our error-message component and new validation rules is ready to use.

Open your app.component.ts file and import the ValidationService

import { ValidationService } from './validation.service';

Then add the rules in the form group

this.registerForm = this.formBuilder.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(6)]],
  confirmPassword: ['', [Validators.required, ValidationService.password]]
},{
  validator: [
    ValidationService.match('password', 'confirmPassword'),
  ]
});

After the changes our app.component.ts file will looks like this

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ValidationService } from './validation.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'helloworld';
  registerForm: FormGroup;
  submitted = false;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', [Validators.required, ValidationService.password ]]
    }, {
      validator: [
        ValidationService.match('password', 'confirmPassword'),
      ]
    });
  
  }

  onSubmit() {
    this.submitted = true;

    // stop the process here if form is invalid
    if (this.registerForm.invalid) {
        return;
    }

    alert('SUCCESS!!');
}

}

Then open the app.component.html file and replace the html with the below html

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Register</h3>
            <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
                <div class="form-group">
                    <label>First Name</label>
                    <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.firstName.errors }" />
                    <error-message [control]="registerForm.controls.firstName" *ngIf="submitted"></error-message>
                </div>
                <div class="form-group">
                    <label>Last Name</label>
                    <input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.lastName.errors }" />
                    <error-message [control]="registerForm.controls.lastName" *ngIf="submitted"></error-message>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.email.errors }" />
                    <error-message [control]="registerForm.controls.email" *ngIf="submitted"></error-message>
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.password.errors }"  />
                    <error-message [control]="registerForm.controls.password" *ngIf="submitted"></error-message>
                </div>
                <div class="form-group">
                    <label>Confirm Password</label>
                    <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.confirmPassword.errors }"  />
                    <error-message [control]="registerForm.controls.confirmPassword" *ngIf="submitted"></error-message>                    
                </div>
                <div class="form-group">
                    <button class="btn btn-primary">Register</button>
                </div>
            </form>
        </div>
    </div>
</div>

Angular8 form validation form will looks like this

37 Comments

  1. ed pills that work quickly said:

    I happen to be writing to make you understand what a useful experience our princess enjoyed going through your blog. She discovered lots of issues, most notably how it is like to have a very effective giving heart to have many others effortlessly gain knowledge of certain extremely tough matters. You really did more than my desires. Many thanks for displaying the helpful, healthy, educational and also easy thoughts on the topic to Gloria. https://hiedmedsout.com/

    January 7, 2021
    Reply
  2. order pamelor said:

    I precisely had to appreciate you all over again. I am not sure the things that I might have followed in the absence of the entire methods documented by you directly on such industry. It had become a real fearsome crisis in my circumstances, however , finding out the skilled form you managed that made me to jump over fulfillment. I’m just happier for this guidance and even hope you find out what a great job you are doing instructing other individuals through your blog post. I am sure you have never encountered all of us. https://pamelornortriptyline.com/

    January 8, 2021
    Reply
  3. buy venlor said:

    I enjoy you because of all your efforts on this site. Ellie enjoys doing internet research and it’s easy to see why. All of us hear all concerning the compelling means you deliver good information by means of the blog and as well cause contribution from other people about this concept plus my daughter is actually being taught a lot. Enjoy the remaining portion of the new year. You’re the one carrying out a first class job. https://venlorz.com/#

    January 9, 2021
    Reply
  4. https://txt2080.com/ said:

    The person might not have enough time to go into detail about their plans. Instead, today we’ll show you just a few phrases to make a quick comment about the person’s upcoming trip to support them.
    When you say the right thing at this moment it will help build the connection between you and your colleague.
    카지노사이트

    January 18, 2021
    Reply
  5. https://www.vfv79.com/theking/ said:

    The most touching goodbyes are the ones that are well said . Create magical moments wherever you go . Most of the time it’s the little words in life that remind you the best . A good expression knows how to separate tears from laughter . A wish from all of us — May you have a trip that’s as beautiful as you’re !
    If English is your second language, Successful English is a good place to find clear explanations and practical suggestions for improving it.
    더킹카지노

    January 18, 2021
    Reply
  6. https://liveone9.com/ said:

    One of a blogger’s toughest tasks is managing the discussions around posts, and determining which comments are valuable and which are spam.
    Whenever you post content, it is almost guaranteed you will receive some spam in your blog comments. People will submit comments that are completely irrelevant to the discussion to get exposure for themselves or drop a link to their website.
    카지노사이트

    January 18, 2021
    Reply
  7. Olive said:

    It is appropriate time to make some plans for
    the future and it’s time to be happy. I have read this
    post and if I could I wish to suggest you some interesting things or tips.

    Perhaps you could write next articles referring to this article.
    I desire to read even more things about it!

    My web site :: cheap flights

    January 31, 2021
    Reply
  8. Kassie said:

    My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s
    tryiong none the less. I’ve been using Movable-type on a
    number of websites for about a year and am anxious about
    switching to another platform. I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress content into it?
    Any help would be really appreciated!

    my website – cheap flights

    February 1, 2021
    Reply
  9. Hope said:

    Hi, just wanted to say, I loved this post.
    It was funny. Keep on posting!

    my webpage; cheap flights

    February 1, 2021
    Reply
  10. Marquis said:

    Hello to all, it’s truly a pleasant for me to pay
    a quick visit this web page, it consists of important Information.

    my blog post … cheap flights – tinyurl.com,

    February 2, 2021
    Reply
  11. Alyssa said:

    Hi there everyone, it’s my first go to see at this website, and
    paragraph is actually fruitful in support of me, keep up posting such articles.

    My blog: cheap flights

    February 2, 2021
    Reply
  12. Reyna said:

    These are actually fantastic ideas in concerning blogging.
    You have touched some good factors here. Any
    way keep up wrinting.

    Also visit my web blog cheap flights (http://tinyurl.com/)

    February 3, 2021
    Reply
  13. NncsGeste said:

    viagra online at boots buy viagra boca who manufactures viagra

    February 4, 2021
    Reply
  14. FvfcGeste said:

    viagra ireland online viagra express buy generic viagra online

    February 4, 2021
    Reply
  15. Fqhhguany said:

    canadian pharmacies without prescriptions cvs online pharmacy pharmacy drug store

    February 4, 2021
    Reply
  16. Ahkdguany said:

    canadian drug stores online skin care overseas pharmacy forum

    February 7, 2021
    Reply
  17. Tabitha said:

    Good day! I know this is kinda off topic but I was
    wondering which blog platform are you using for
    this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m
    looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

    Feel free to surf to my web blog :: 카지노사이트

    February 10, 2021
    Reply
  18. Alfredo said:

    It’s actually a great and useful piece of information. I am glad that you simply shared this useful
    information with us. Please stay us informed
    like this. Thanks for sharing.

    my homepage cheap flights (tinyurl.com)

    February 12, 2021
    Reply
  19. FbsgGeste said:

    cialis free offer cialis buy cialis with american express

    February 12, 2021
    Reply
  20. Britney said:

    Great American Novels Everyone Should Read Alias Grace Novel Review

    Also visit my homepage – pdf wordpress

    February 16, 2021
    Reply
  21. Helena said:

    The Body Keeps The Score Book Depository 1984 Book Reddit

    My web blog; pdf books

    February 16, 2021
    Reply
  22. Ilse said:

    K12 Education Technology News Bseb 10th Result Verification

    Take a look at my site :: pdf book

    February 16, 2021
    Reply
  23. Lauri said:

    Ferdinand The Bull Summary Multicultural Literature In Education

    Have a look at my web blog :: pdf wordpress (iratgradzio1972.netlify.app)

    February 17, 2021
    Reply
  24. Troy said:

    Amazon Uk The Subtle Art Of Not Giving The Rosie Project Knjiga

    my page: wordpress.org

    February 17, 2021
    Reply
  25. Donaldcep said:

    Very good written text.

    free robux

    February 17, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *