Reactive Forms Validation Using Angular

  • Using the following line in the Command Prompt, we first established a project.
ng new formValidation
  • First, we must import ReactiveFormsModule into App-Module using the code shown below.
  1. App.Module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule, ReactiveFormsModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
  • Now that we need to develop a React-form in Angular, we need to include several dependencies in the app, component.ts file, such as FormBuilder, FormGroup, and Validators.
import { FormBuilder, FormGroup } from '@angular/forms';
  • and build a FormBuilder object in the app component’s function Object() { [native code] } as shown below,
constructor(private formBuilder: FormBuilder) { }
  • To define a form in HTML, the FromGroup directive must be used, and formControlName must be used to provide the control name.
<form [formGroup]="form">
    <div class="form-group">
      <label>Full Name</label>
      <input type="text" formControlName="fullname" class="form-control" />
    </div>

    <div class="form-group">
      <label>Username</label>
      <input type="text" formControlName="username"
        class="form-control"/>
    </div>
</div>
  • We must import some dependencies for validation in order to apply validation, such as
import {AbstractControl, Validators } from '@angular/forms';
  • Using AbstractControl and ValidatorFn, you can create a custom validator like the code below:
import { AbstractControl, ValidatorFn } from '@angular/forms';

export default class Validation {
  static match(controlName: string, checkControlName: string): ValidatorFn {
    return (controls: AbstractControl) => {
      const control = controls.get(controlName);
      const checkControl = controls.get(checkControlName);

      if (checkControl.errors && !checkControl.errors.matching) {
        return null;
      }

      if (control.value !== checkControl.value) {
        controls.get(checkControlName).setErrors({ matching: true });
        return { matching: true };
      } else {
        return null;
      }
    };
  }
}
  1. app.component.ts
import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import Validation from './utils/validation';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  submitted = false;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.formBuilder.group(
      {
        fullname: ['', Validators.required],
        username: [
          '',
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(20)
          ]
        ],
        email: ['', [Validators.required, Validators.email]],
        password: [
          '',
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(40)
          ]
        ],
        confirmPassword: ['', Validators.required],
        acceptTerms: [false, Validators.requiredTrue]
      },
      {
        validators: [Validation.match('password', 'confirmPassword')]
      }
    );
  }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  onSubmit(): void {
    this.submitted = true;

    if (this.form.invalid) {
      return;
    }

    console.log(JSON.stringify(this.form.value, null, 2));
  }

  onReset(): void {
    this.submitted = false;
    this.form.reset();
  }
}
  1. App.Component.html
<div class="register-form">
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label>Full Name</label>
      <input
        type="text"
        formControlName="fullname"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.fullname.errors }"/>
      <div *ngIf="submitted && f.fullname.errors" class="invalid-feedback">
        <div *ngIf="f.fullname.errors.required">Fullname is required</div>
      </div>
    </div>

    <div class="form-group">
      <label>Username</label>
      <input
        type="text"
        formControlName="username"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.username.errors }"/>
      <div *ngIf="submitted && f.username.errors" class="invalid-feedback">
        <div *ngIf="f.username.errors.required">Username is required</div>
        <div *ngIf="f.username.errors.minlength">
          Username must be at least 6 characters
        </div>
        <div *ngIf="f.username.errors.maxlength">
          Username must not exceed 20 characters
        </div>
      </div>
    </div>

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

    <div class="form-group">
      <label>Password</label>
      <input
        type="password"
        formControlName="password"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.password.errors }"/>
      <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
        <div *ngIf="f.password.errors.required">Password is required</div>
        <div *ngIf="f.password.errors.minlength">
          Password must be at least 6 characters
        </div>
        <div *ngIf="f.password.errors.maxlength">
          Username must not exceed 40 characters
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Confirm Password</label>
      <input
        type="password"
        formControlName="confirmPassword"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }"/>
      <div
        *ngIf="submitted && f.confirmPassword.errors"
        class="invalid-feedback">
        <div *ngIf="f.confirmPassword.errors.required">
          Confirm Password is required
        </div>
        <div *ngIf="f.confirmPassword.errors.matching">
          Confirm Password does not match
        </div>
      </div>
    </div>

    <div class="form-group form-check">
      <input
        type="checkbox"
        formControlName="acceptTerms"
        class="form-check-input"
        [ngClass]="{ 'is-invalid': submitted && f.acceptTerms.errors }"/>
      <label for="acceptTerms" class="form-check-label"
        >I have read and agree to the Terms</label>
      <div *ngIf="submitted && f.acceptTerms.errors" class="invalid-feedback">
        Accept Terms is required
      </div>
    </div>

    <div class="form-group">
      <button type="submit" class="btn btn-primary">Register</button>
      <button
        type="button"
        (click)="onReset()"
        class="btn btn-warning float-right">
        Reset
      </button>
    </div>
  </form>
</div>
  • Using the following command, let’s begin the project:
  1. ng serve
  • Output :

Submit a Comment

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

Subscribe

Select Categories