Friday, October 2, 2020

Angular reactive form validation

 In this tutorial, we will discuss the form validation in angular. If you are developing any kind of application, it is necessary to validate your form control before submitting the form. There are two types of form validation in angular reactive form validation, template-driven form validation both are having different behavior comparing another one.

What is reactive form validation in angular?

The reactive form uses synchronous communication between the view and model, and it is returning the new form state of every control input change. In short, when view loading the form control validation attached to the respective control according to the validator declared in the form group. If any input changes happening, it is returning the status valid or invalid.

How to validate the radio button, checkbox, dropdown in angular using reactive form?.

angular reactive form validation example

  • Import ReactiveFormsModule in the App.module file import declaration from '@angular/forms' library.
  • Declare ReactiveFormsModule  in import declaration.

app.module.ts

import {ReactiveFormsModule } from '@angular/forms'; 
imports: [
     ReactiveFormsModule 
  ],
  • Create a component in the name of reactive-form-validation using the command of ng g c reactive-form-validation.
  • Import FormGroup, FormBuilder, Validators in the reactive-form-validation.ts file import declaration from '@angular/forms' library .
  • Declare FormGroup variable as angForm.
  • Declare FormBuilder variable as fb in the constructor parameter.
  • Within the constructor building the form group so that initially we can attach the validation.

reactive-form-validation.ts

import { FormGroup, FormBuilder,  Validators } from '@angular/forms';
 
angForm: FormGroup;
  constructor(private fb:FormBuilder) {
    this.angForm=this.fb.group({
      firstname :['',[Validators.required,Validators.minLength(10)]],
      lastname :['',Validators.required],
      email :['',[Validators.required,Validators.email]],
      password :['',Validators.required],
      mobile :['',Validators.required],
      address :['',Validators.required],
       agree :['',Validators.requiredTrue],
      city :['',Validators.required],
     gender :['',Validators.required]
    });
   }
  • Grouping all control and assigning in the angForm.
  • Validators.required  -  Required field validation
  • Validators.minLength(10)  -  Minimum 10 character validation.
  • Validators.email  -  Angular default email valiator.
  • Validators.requiredTrue  -  Checkbox  checked true validation

reactive-form-validation.html

 <form [formGroup]="angForm" >
 <input type="text"  formControlName="firstname">
 <button type="submit"  [disabled]="!angForm.valid" >Submit</button>
</form>
  • [formGroup]="angForm"  -  Form group property binding value as angForm. It should be the same as the ts file variable declared.
  • formControlName="firstname"  -  Every control name identification. It should be also same as declared in the ts file.
  •  [disabled]="!angForm.valid"  -  Finally disabled the button if form state is invalid. The button should be enabled if form state is valid.

 

How to submit the form in angular after the form status valid? 

  • Add FormsModule in the App.module import declaration from '@angular/forms'
  • Declare ReactiveFormsModule in the import declaration.
  • Add event binding in HTML file form tag (ngSubmit)="postdata(angForm)".
  • Add NgForm in the reactive-form-validation.ts import declaration from '@angular/forms'.
  • Create function for postdata() within in the class file

app.module.ts

import {FormsModule,ReactiveFormsModule } from '@angular/forms'; 
imports: [
     ReactiveFormsModule,
FormsModule 
  ],

reactive-form-validation.ts

import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
export class ReactiveFormValidationComponent implements OnInit {
...
postdata(angForm1:NgForm)
  {
    console.log(angForm1.controls);
  }
}
 

reactive-form-validation.html

<form [formGroup]="angForm" (ngSubmit)="postdata(angForm)">
 

How to display error messages using angular reactive form validation?

<label for="email">Email</label>
        <input type="email" class="form-control" formControlName="email" autocomplete="nope" id="email"
          placeholder="Email">
          <div *ngIf="!email?.valid && (email?.dirty ||email?.touched)"> 
            <span class="frmerror" [hidden]="!email?.errors.required" >
              Email id required.
            </span>
            <span class="frmerror" [hidden]="!email?.errors.email" >
              Invalid Email.
            </span>
          </div>
email: ['', [Validators.required,Validators.minLength(1), Validators.email]],
get email() { return this.angForm.get('email'); }

 

  •  *ngIf="!email?.valid && (email?.dirty ||email?.touched)"  -  If email is invalid and input focus time only the div displayed.
  • Displaying span error messages through hidden properties.
  • get email() { return this.angForm.get('email'); }  -  In ts file get the email value through the return function

Find below the full code.

reactive-form-validation.html

<div class="jumbotron">
  <form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off">
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="firstname">First Name</label>
        <input type="text" class="form-control" formControlName="firstname" autocomplete="nope" id="firstname"
          placeholder="First Name">
          <div *ngIf="!firstname?.valid && (firstname?.dirty ||firstname?.touched)"> 
            <span class="frmerror" [hidden]="!firstname?.errors.required" >
              First Name required.
            </span>
            <span class="frmerror" [hidden]="!firstname?.errors.minlength" >
              Minimum 4 character required.
            </span>
          </div> 
      </div>
 
      <div class="form-group col-md-6">
        <label for="lastname">Last Name</label>
        <input type="text" class="form-control" formControlName="lastname" autocomplete="nope" id="lastname"
          placeholder="Last Name">
          <div *ngIf="!lastname?.valid && (lastname?.dirty ||lastname?.touched)"> 
            <span class="frmerror" [hidden]="!lastname?.errors.required" >
              Last Name required.
            </span>
 
          </div> 
      </div>
    </div>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="email">Email</label>
        <input type="email" class="form-control" formControlName="email" autocomplete="nope" id="email"
          placeholder="Email">
          <div *ngIf="!email?.valid && (email?.dirty ||email?.touched)"> 
            <span class="frmerror" [hidden]="!email?.errors.required" >
              Email id required.
            </span>
            <span class="frmerror" [hidden]="!email?.errors.email" >
              Invalid Email.
            </span>
          </div> 
      </div>
      <div class="form-group col-md-6">
        <label for="password">Password</label>
        <input type="password" class="form-control" formControlName="password" autocomplete="nope" id="password"
          placeholder="Password">
          <div *ngIf="!password?.valid && (password?.dirty ||password?.touched)"> 
            <span class="frmerror" [hidden]="!password?.errors.required" >
              Password required.
            </span>
 
          </div> 
      </div>
    </div>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="mobile">Mobile No</label>
        <input type="text" class="form-control" formControlName="mobile" autocomplete="nope" id="mobile">
        <div *ngIf="!mobile?.valid && (mobile?.dirty ||mobile?.touched)"> 
          <span class="frmerror" [hidden]="!mobile?.errors.required" >
            Mobile No required.
          </span>
 
        </div> 
 
 
 
      </div>
      <div class="form-group col-md-6">
        <label for="city">City</label>
        <select id="city" formControlName="city" class="form-control">
          <option selected>Choose...</option>
          <option>Thailand</option>
          <option>US</option>
          <option>UK</option>
        </select>
        <div *ngIf="!city?.valid && (city?.dirty ||city?.touched)"> 
          <span class="frmerror" [hidden]="!city?.errors.required" >
            City required.
          </span>
 
        </div> 
      </div>
    </div>
    <div class="form-group">
      <label for="address">Address</label>
      <input type="text" class="form-control" formControlName="address" autocomplete="nope" id="inputAddress"
        placeholder="1234 Main St">
        <div *ngIf="!address?.valid && (address?.dirty ||address?.touched)"> 
          <span class="frmerror" [hidden]="!address?.errors.required" >
            Address required.
          </span>
 
        </div> 
    </div>
    <div class="form-row">
      <div class="form-group col-md-4">
        <div class="custom-control custom-radio">
          <input type="radio" id="male" formControlName="gender" value="Male" name="gender"
            class="custom-control-input">
          <label class="custom-control-label" for="male">Male</label>
        </div>
      </div>
      <div class="form-group col-md-4">
        <div class="custom-control custom-radio">
          <input type="radio" id="female" formControlName="gender" value="Female" name="gender"
            class="custom-control-input">
          <label class="custom-control-label" for="female">Female</label>
        </div>
      </div>
      <div class="form-group col-md-4">
        <div class="custom-control custom-radio">
          <input type="radio" id="other" formControlName="gender" value="Other" name="gender"
            class="custom-control-input">
          <label class="custom-control-label" for="other">Other</label>
        </div>
      </div>
      <div class="form-group col-md-12" > 
        <span class="frmerror" [hidden]="!gender?.errors.required" >
          Required.
        </span>
 
      </div> 
    </div>
    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" formControlName="agree" type="checkbox" id="agree">
        <label class="form-check-label" for="agree">
          I agree
        </label>
 
          <span class="frmerror" [hidden]="!agree?.errors.required" >
            Required.
          </span>
 
 
      </div>
    </div>
    <button type="submit" class="btn btn-primary" [disabled]="!angForm.valid">Submit</button>
  </form>
</div>

reactive-form-validation.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '@angular/forms';
 
@Component({
  selector: 'app-reactive-form-validation',
  templateUrl: './reactive-form-validation.component.html',
  styleUrls: ['./reactive-form-validation.component.css']
})
export class ReactiveFormValidationComponent implements OnInit {
  angForm: FormGroup;
  constructor(private fb: FormBuilder) {
 
    this.angForm = this.fb.group({
      firstname: ['', [Validators.required, Validators.minLength(4)]],
      lastname: ['', Validators.required],
      email: ['', [Validators.required,Validators.minLength(1), Validators.email]],
      password: ['', Validators.required],
      mobile: ['', Validators.required],
      address: ['', Validators.required],
      agree: ['', Validators.requiredTrue],
      city: ['', Validators.required],
      gender: ['', Validators.required]
    });
 
  }
 
  ngOnInit() {
 
  }
  postdata(angForm1:NgForm)
  {
    console.log(angForm1.controls);
  }
  get firstname() { return this.angForm.get('firstname'); }
  get lastname() { return this.angForm.get('lastname'); }
  get email() { return this.angForm.get('email'); }
  get password() { return this.angForm.get('password'); }
  get mobile() { return this.angForm.get('mobile'); }
  get address() { return this.angForm.get('address'); }
  get agree() { return this.angForm.get('agree'); }
  get city() { return this.angForm.get('city'); }
  get gender() { return this.angForm.get('gender'); }
 
}
 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import {ReactiveFormsModule,FormsModule } from '@angular/forms'; 
 
  imports: [
     ReactiveFormsModule,FormsModule 
  ],
 

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...