How to validate a reactive form on submit?

angular 4 form validation on submit
angular 7 form validation example
password and confirm password validation in angular 4 reactive form
angular material form validation on submit
angular async validator
angular check if form is valid
angular 4 form validation on submit example
reactive form get value

I am using a reactive form for my application i want to validate the form on submit but i am not able to do that. Here is my code can anyone let me know what i am doing wrong or missing.

This is my form Builder

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ViewController,LoadingController, Events,AlertController } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { MyinfoService} from '../../../../providers/app-services/myinfo/myinfo.service';

private formBuilder: FormBuilder) {
      this.licenseinfo = navParams.get('licenseinfo');
      this.startDate = this.licenseinfo.dlIssued_date;
      this.expiryDate= this.licenseinfo.dlExpiry_date;
      console.log(this.startDate);
      this.todo = this.formBuilder.group({
        issued_state  : ['', Validators.required],
        license_no    : ['', Validators.required],
        name          : ['', Validators.required],
        status        : ['Pending'],
        issued_date   : ['',Validators.required],
        expiry_date   : ['',Validators.required],
        address_line1 : ['',Validators.required],
        address_line2 : [''],
        city          : ['',Validators.required],
        zipcode: ['',Validators.required],
        state  : ['',Validators.required],
        employee_id   : ['']
      });
    }

This is my form

<ion-header>

    <ion-navbar>
      <ion-buttons start>
        <button ion-button (click)="dismiss()">Close</button>
      </ion-buttons>
      <ion-title>License Info Edit</ion-title>
    </ion-navbar>

  </ion-header>


  <ion-content padding>  
    <form [formGroup]="todo" (ngSubmit)="saveMyinfoLicenseinfo()">
      <ion-item>
        <ion-label stacked class="requiredLabel"> State Issued By</ion-label>
        <ion-input value="{{licenseinfo.issued_state}}" formControlName="issued_state"></ion-input>
      </ion-item> 

      <ion-item>
        <ion-label stacked class="requiredLabel">Driver Lic. No</ion-label>
        <ion-input type="text" value="{{licenseinfo.driver_lic_no}}" formControlName="license_no"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Name on DL</ion-label>
        <ion-input value="{{licenseinfo.name}}" formControlName="name"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Date Issued</ion-label>
        <ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="DD MMM YYYY" formControlName="issued_date" [(ngModel)]="startDate" ></ion-datetime>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Expiry Date</ion-label>
        <ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="DD MMM YYYY" formControlName="expiry_date" [(ngModel)]="expiryDate" ></ion-datetime>
      </ion-item>

      <ion-item>
          <ion-label stacked class="requiredLabel">Address Line1</ion-label>
          <ion-input value="{{licenseinfo.address_line1}}" formControlName="address_line1"></ion-input>
        </ion-item>

      <ion-item>
          <ion-label stacked >Address Line2</ion-label>
          <ion-input value="{{licenseinfo.address_line2}}" formControlName="address_line2"></ion-input>
        </ion-item>
      <ion-item>
          <ion-label stacked class="requiredLabel">City</ion-label>
          <ion-input value="{{licenseinfo.city}}" formControlName="city"></ion-input>
        </ion-item>

      <ion-item>
          <ion-label stacked class="requiredLabel">State</ion-label>
          <ion-input value="{{licenseinfo.issued_state}}" formControlName="issued_state"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked class="requiredLabel">Zipcode</ion-label>
          <ion-input value="{{licenseinfo.zipcode}}" formControlName="zipcode"></ion-input>
        </ion-item>

      <ion-input value="{{employee_id}}" formControlName="employee_id" hidden></ion-input>
      <ion-row>
        <ion-col>
          <button ion-button type="button" color="dark" outline block margin-top (click)="dismiss()">Cancel</button>
        </ion-col>
        <ion-col>
          <button ion-button type="submit" color="dark" margin-top block>Save</button>
        </ion-col>
      </ion-row>
    </form>
  </ion-content>

This is my on Submit code:

saveMyinfoLicenseinfo(){
    if(this.todo.valid){
    let loading = this.loadingCtrl.create({});
    loading.present();
    this.myinfoService.saveLicenseDetails(this.todo.value).subscribe(data => {
      loading.dismiss();        
        if(data.isSuccessful){
          this.viewCtrl.dismiss(true);
        }
        else
          this.viewCtrl.dismiss(false);
      });
      this.submitted = true;
    }
    else{
      this.validateAllFields(this.todo);
    }
}
validateAllFields(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
      const control = formGroup.get(field);            
      if (control instanceof FormControl) {             
          control.markAsTouched({ onlySelf: true });
          console.log(3);
      } else if (control instanceof FormGroup) {        
          this.validateAllFields(control);  
          console.log(this.validateAllFields(control));
      }
  });
}

so i am calling the onsubmit on to this function and if the form is not valid then i am trying to make all the feilds as touched but the color of the feilds is not changing even after submit. Can i know is this the right way to go? or Is there a better way of doing it?

You have defined the validators the wrong way, check the official documentation it will help you Form Validation

The correct way to do it is this:

this.heroForm = new FormGroup({
  'name': new FormControl(this.hero.name, [
    Validators.required,
    Validators.minLength(4),
    forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
  ]),
  'alterEgo': new FormControl(this.hero.alterEgo),
  'power': new FormControl(this.hero.power, Validators.required)
});

Angular 2 Reactive Forms trigger validation on submit, The onSubmit method will print the content of the form on the console if the form is valid and submitted successfully. Open reactive-form. Take a look at the Reactive form validation section of the Angular docs for examples on: how to get information on the validity of each field in the template, and; how to add HTML to show errors alongside/within the form (if desired) The ngClass directive might be very helpful in dynamically assigning a specific class to an invalid form field. You can then code appropriate CSS in the accompanying CSS file, or utilise any classes that Ionic might provide specifically for invalid form entries.

Your invalid form fields don't change colour on submit because you don't appear to have set up any CSS (or CSS classes) for fields with invalid values.

Take a look at the Reactive form validation section of the Angular docs for examples on:

  1. how to get information on the validity of each field in the template, and
  2. how to add HTML to show errors alongside/within the form (if desired)

The ngClass directive might be very helpful in dynamically assigning a specific class to an invalid form field. You can then code appropriate CSS in the accompanying CSS file, or utilise any classes that Ionic might provide specifically for invalid form entries.

Angular 7, If you're new to forms, start by reviewing the Forms and Reactive Forms guides. Every time the value of a form control changes, Angular runs validation and by changing the updateOn property from change (default) to submit or blur . Reactive forms are one of the ways to add form validation to your app. They work by validating your models in the component code, as opposed to the alternative, which is to add form validation

try with this Html code.

<form [formGroup]="todo" #f="ngForm" (ngSubmit)='saveMyinfoLicenseinfo()' novalidate>

        <ion-item class="Your css class">
            <ion-input type="text"  formControlName="name"></ion-input>
        </ion-item>
        <div *ngIf="f.submitted && todo.controls.name.errors?.required" class="Error class ">Please enter Name</div>            


        <ion-item>
            <button ion-button outline>GO</button>
        </ion-item>

</form>

How to Validate Angular Reactive Forms, Reactive forms provide a model-driven approach to handling form inputs whose update a basic form control, progress to using multiple controls in a group, validate The FormGroup directive listens for the submit event emitted by the formĀ  The form binds the form submit event to the onSubmit() handler in the app component using the Angular event binding (ngSubmit)="onSubmit()". Validation messages are displayed only after the user attempts to submit the form for the first time, this is controlled with the submitted property of the app component.

Form validation, Also we assign our onSubmit callback. The form itself does only contain of some input fields and a select-element. src/app/contact/contact. Reactive Forms Validation App Template. The app component template contains all the html markup for displaying the example registration form in your browser. The form element uses the [formGroup] directive to bind to the registerForm FormGroup in the app component above. The form binds the form submit event to the onSubmit()

Reactive forms, updateOn: 'blur' and updateOn: 'submit' are the options we were really craving for while working with Angular Forms In Angular 5 , two new form validation techniques are introduced. https://angular.io/guide/reactive-forms. Problem. The form will validate on submit if left blank, but even after filling the value when I check this.testform.valid it returns false.But if I remove updateOn:'submit' on form then it validates on blur of input control and when value is entered it validates form return true.

Validating Reactive Forms in Angular, But i also need to be able to enable the submit button by default. Expected behavior. Instead of validating form on value change, can we have oneĀ  Validating Reactive Forms in Angular Forms are a fundamental part of every angular application. One of the greatest features of forms is, that you can validate the input of the user before it is send to the server.

Comments
  • I don't see anything in the HTML that would cause a colour change when a field becomes touched. Is this in the external CSS file?
  • no, I thought the default validation for the fields using the form builder validation will be used. Normally when the fields are touched there will be a validation so i want to manually make all the fields touched.
  • Show us your imports
  • import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams,ViewController,LoadingController, Events,AlertController } from 'ionic-angular'; import {Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { MyinfoService} from '../../../../providers/app-services/myinfo/myinfo.service'; /** @Exterminator
  • If I understand correctly, when validation fails, you call the validateAllFields method on the form, which appears to iterate over all the FormControls, "touch" them, and log 3 to the console each time. What's your intended result of calling this method?
  • I think that's, not a problem because we can use form builders for validating the forms instead of form Groups as specified in the Documentation. The problem is that validation is not initiating on dynamic Touch of the fields.