Web
Analytics
How to Implement Conditional Validation in Angular 4 Model-driven Forms | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

In this article , I am going to show you how we can implement angular validation on button click or angular validation on submit button. In article model driven reactive form I demonstrate that how we can create an angular form using formgroup and formcontrol or model-driven angular form. In that article, I created a form which shows validation error after control touched state and submit button was disabled until all validation errors removed by the user. Most of the viewers asked me that how we can call validations manually or by the button click.

In this article, I am going to show you that how we can trigger validation on submit button. I am taking some code from my last article.




Step1: Create new component reactiveformex

ng g c reactiveformex

Step2: Write the following code into the reactive form component(reactiveformex.component.ts).

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

@Component({
  selector: 'app-reactiveformex',
  templateUrl: './reactiveformex.component.html',
  styleUrls: ['./reactiveformex.component.css']
})
export class ReactiveformexComponent implements OnInit {

  // Write regular expression to validate email id
  EMAIL_REGEX = "[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*";
  // Create object of FormGroup
registrationForm: FormGroup;
  constructor() { }

  ngOnInit() {

    // Initilize formgroup throgh formcontrol and apply validations
    this.registrationForm = new FormGroup({
fname: new FormControl('', Validators.required),
lname: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.pattern(this.EMAIL_REGEX)])

    });
  }
  // following method is used to call or trigger validations on button click.
  
  validateform()
  {
    // As we know that when user does not fill any value and click on submit button in that 
    // condition form will be invalid 
    if(this.registrationForm.invalid){
      // Validation errors are called when user put focus on control but does't fill any value or wrong values
      // So we are making our control touched
      this.registrationForm.get('fname').markAsTouched();
      this.registrationForm.get('lname').markAsTouched();
      this.registrationForm.get('email').markAsTouched();
      // return false to prevent form submit
return false;
    }
  }
  onSubmit(formvalue)
  {
    console.log(formvalue);
    console.log(this.registrationForm.value);
  }

}




Step 3: Add the following code into reactiveformex.component.html

<p>
  reactiveformex works!
</p>
<form novalidate [formGroup]="registrationForm"  (ngSubmit)="onSubmit(registrationForm.value)">  
<input  type="text" class="form-control" formControlName="fname" >
<div class="error-message"  *ngIf="registrationForm.get('fname').touched && registrationForm.get('fname').hasError('required')"> 
    The First name is required.  
   </div>  

<input  type="text" class="form-control" formControlName="lname" >
<div class="error-message"  *ngIf="registrationForm.get('lname').touched && registrationForm.get('lname').hasError('required')"> 
    The Last name is required.  
   </div> 
  <input type="email" class="form-control" formControlName="email">
    <div class="error-message"  *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('required')"> 
         The email is required.  
        </div>  
        <div class="error-message" *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('pattern')">  
            The email format should be <i>yogeshdotnet@gmail.com</i>  </div>
            <!-- Below click event is called before submit -->
              <button type="submit" class="btn btn-secondary"  (click)="validateform()" >Submit</button>
            
 </form>

Step 4: Add reference of the newly created component into app.component.html

<app-reactiveformex></app-reactiveformex>

Step 5: Run program

ng serve --o

Output