1
votes

I want to check all the validations of the form fields on click of submit button and fire missing or wrong field validation before submitting data

like in previous version of angular on submit we can fire all error validation if form state is invalid

if (scope.sampleForm.$valid) {
 // success code
} else {
    angular.forEach(scope.sampleForm.$error, function (field) {
           angular.forEach(field, function (errorField) {
                  errorField.$setTouched();
           })
    });                   
}

I check many answer related to this and most answer is disabled submit button if form is invalid, I want to achieve this without disabling button, please suggest me how I can do achieve this? I am using template driven approach angular (v4)

2
Hey, did either of the answers help you? :) - AJT82
Yes your answer meet my requirement - krishna

2 Answers

0
votes

You have to add html name attribute to each input of the form. The name attribute specifies the name of the property on the form instance.

<form #f="ngForm" novalidate>

<md-input-container>
  <input mdInput type="text"
         placeholder="Name"
         name = "name"
         [(ngModel)] = "user.name"
         #userName = "ngModel"
         minlength="4"
         required
         nameRahul>
</md-input-container>
<div *ngIf="formErrors.name[0]">
  <div *ngFor = "let data of formErrors.name" class="alert alert-danger">
    {{data}}
  </div>
</div>
</form>

You can make use of form controls and check if the field is dirty Check these two files for better understanding

https://github.com/rahulrsingh09/AngularConcepts/blob/master/src/app/template-driven/template-driven.component.html

https://github.com/rahulrsingh09/AngularConcepts/blob/master/src/app/template-driven/template-driven.component.ts

https://rahulrsingh09.github.io/AngularConcepts/#/template

0
votes

How about introducing a new variable, e.g submitted and then set condition something like the following for example for form control firstname:

<div *ngIf="submitted && !firstname.valid">
  <!-- Error messages here -->
</div>

And on your submit method you just set this flag as true if the form is not valid:

(ngSubmit)="onSubmit(myForm)"

TS:

onSubmit(form) {
  if(!form.valid) {
    this.submitted = true;
  }
  else {
    // valid, do something
  }
}