DEV Community

Cover image for Angular 8/9 Reactive Form Validation Example and Tutorial
Pankaj Kumar
Pankaj Kumar

Posted on

Angular 8/9 Reactive Form Validation Example and Tutorial

In this demo, We will create form validation in Angular 8 using Reactive Form. The form will contain full name, email, phone, password, confirm password and a checkbox. All the fields of the form are required to have some value with the checkbox checked. In this demo, we will also use a validator to show an alert if the user entered the password and confirm password doesn't match.

Let's Get Started

Step 1: Update app.component.ts

I assume that you have created a basic app of angular, Now open the app.component.ts file and put below code in this:


import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { ConfirmEqualValidatorDirective } from './confirm-equal-validator.directive';

declare var NgForm:any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  registerForm: FormGroup;
  submitted = false;

  constructor(private formBuilder: FormBuilder) { }
  title = 'reactive-form-validation-in-angular8';

  ngOnInit() {
  this.registerForm = this.formBuilder.group({
  fullName: ['', Validators.required],
  email: ['', [Validators.required,Validators.email]],
  phone: ['', Validators.required],
  password: ['', [Validators.required,Validators.minLength(6)]],
  confirmPassword: ['', Validators.required],
  tnc: ['', Validators.required]
 });

 }

  get fval() {
  return this.registerForm.controls;
  }
  //this.user.fullName='';
  signup(){
  this.submitted = true;
  if (this.registerForm.invalid) {
  return;
  }
  alert('form fields are validated successfully!');
  }
}

Enter fullscreen mode Exit fullscreen mode

In the above code, At the top we have imported FormBuilder, FormGroup, Validators from angular/forms library. Below that, We can see the form fields and validators for our registration form using Angular FormBuilder to create an instance of a FormGroup that is stored in the registerForm property. After that, the form is bound to the form in the app template below using the formGroup directive.

There is a getter fval as a convenience property to make it easier to access form controls from the template. So we can access, fullName with fval.fullName in place of registrationForm.controls.fullName.

Step 2: Update app.component.html

Open app.component.html file and put below code:


<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<form [formGroup]="registerForm" (ngSubmit)="signup();">
<div class="formbox">

<div class="form-group">
<input type="text" formControlName="fullName" class="form-control" placeholder="Full Name" [ngClass]="{ 'is-invalid': submitted && fval.fullName.errors }"/>
<div *ngIf="submitted && fval.fullName.errors" class="invalid-feedback">
<div *ngIf="fval.fullName.errors.required">
Full Name is required and must be a valid name
</div>

</div>
</div>
<div class="form-group">
<input type="email" formControlName="email" class="form-control" placeholder="Email" [ngClass]="{ 'is-invalid': submitted && fval.email.errors }" />
<div *ngIf="submitted && fval.email.errors" class="invalid-feedback">

<div *ngIf="fval.email.errors.required">Email is required</div>

<div *ngIf="fval.email.errors.email">Enter a valid email address</div>
</div>
</div>

<div class="form-group">
<input type="text" formControlName="phone" class="form-control" placeholder="Phone No." maxlength="12" minlength="10" [ngClass]="{ 'is-invalid': submitted && fval.phone.invalid }" required />
<div *ngIf="submitted && fval.phone.errors" class="invalid-feedback">
<div *ngIf="fval.phone.errors.required">Phone is required</div>
</div>
</div>
<div class="form-group">
<input type="password" formControlName="password" class="form-control" placeholder="Password" [ngClass]="{ 'is-invalid': submitted && fval.password.errors}" />
<div *ngIf="submitted && fval.password.errors"class="invalid-feedback">
<div ngClass="fval.password.errors.required">
Password is required.
</div>
<div *ngIf="fval.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<input type="password" formControlName="confirmPassword" class="form-control" placeholder="Confirm Password"[ngClass]="{ 'is-invalid': submitted && fval.confirmPassword.errors }" appConfirmEqualValidator='password'/>
<div *ngIf="submitted && fval.confirmPassword.errors" class="invalid-feedback">
<div *ngIf="fval.confirmPassword.errors.required"
>Confirm password is required</div>
<div *ngIf="fval.confirmPassword.errors?.notEqual">Password Mismatch</div>
</div>

</div>
<div class="form-group">
<div class="checkboxrow">
<input type="checkbox" class="form-check-input" id="tnc" formControlName="tnc" [ngClass]="{ 'is-invalid': submitted && fval.tnc.errors }">
<label for="tnc" class="form-check-label">Agree with terms and conditions</label>

<div *ngIf="submitted && fval.tnc.errors" class="invalid-feedback">
<div>Please agree with terms and conditions</div>
</div>
</div>
</div>

<div class="form-group">
<button type="submit" class="btn btn-primary signin">Sign Up <span class="arrowbtn"><span
class="fa fa-arrow-right"></span></span></button>
</div>
</div>
</form>
</div>
</div>
</div>

Enter fullscreen mode Exit fullscreen mode

In the above code, We can see all the fields used in the register form. The form element uses the [formGroup] directive to bind the registrationForm FormGroup in the app.component.ts file.

On submit of the form, the signup method inside the app component is called. For now, the signup method shows an alert in case of successful validated form.

Step 3: Create a directive for password and confirm password match

create a file named confirm-equal-validator.directive.ts inside app folder and put below code inside it.


import { Validator,NG_VALIDATORS, AbstractControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';

@Directive({
selector:'[appConfirmEqualValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: ConfirmEqualValidatorDirective,
multi: true
}]
})

export class ConfirmEqualValidatorDirective implements Validator {
@Input() appConfirmEqualValidator: string;

validate(control: AbstractControl):{[key:string]: any} |null {
const controlToCompare = control.parent.get(this.appConfirmEqualValidator);

if(controlToCompare && controlToCompare.value !==control.value){
return { 'notEqual': true}
}
return null;
}
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Update app.module.ts

Put below code in side app.module.ts


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

import { AppComponent } from './app.component';
import { ConfirmEqualValidatorDirective } from './confirm-equal-validator.directive';

@NgModule({
declarations: [
AppComponent,ConfirmEqualValidatorDirective
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Enter fullscreen mode Exit fullscreen mode

Step 5: Run the app

Run the app with npm start over terminal and check the browser over url http://localhost:4200/. You will see validation message like below after submitting empty form.

Image description

Conclusion

So in this article, I explained how to validate form with reactive form validation in the Angular 8 application. If you are new to Angular then click here to find many demos to start the app for enterprise-level application

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!

This article is originally posted over jsonworld

Top comments (0)