Home:ALL Converter>Show form validation errors on submit in angular template driven form

Show form validation errors on submit in angular template driven form

Ask Time:2018-06-08T08:24:40         Author:Upendra Sachan

Json Formatter

I have created template driven form in Angular.

<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<input type="text" class="form-control" name="fullName" #fullName="ngModel" required>
<div *ngIf="fullName.errors?.required && fullName.touched" class="validation-message">Required</div>
<button type="submit">Post</button>

It shows error when it is invalid and touched. I need to display error when form is submitted i.e. when the submit button is clicked.

onSubmit({value, valid}): void {
    if (valid) {
      console.log(value);
    } else {
      console.log('invalid form');
    }
  }

Author:Upendra Sachan,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50751793/show-form-validation-errors-on-submit-in-angular-template-driven-form
esnezz :

In onSubmit method iterate through all form controls and simply mark them as touched\n\nObject.keys(form.controls).forEach(key => {\n form.controls[key].markAsTouched();\n});\n",
2019-10-14T19:12:27
Vega :

Set a flag to be true when it's valid and use $ngIf:\nHTML\n\n<form #myForm=\"ngForm\" (submit)=\"onSubmit(myForm)\">\n <input type=\"text\" class=\"form-control\" required [(ngModel)]=\"fullname\" name=\"fullname\" #input=\"ngModel\">\n <div style=\"color:red\" *ngIf=\"submittedError\">\n Error\n </div>\n <br><br>\n <button type=\"submit\">Post</button>\n</form>\n\n\nTypescript:\n\nsubmittedError;\n... \nonSubmit({value, valid}): void {\n if (valid) {\n this.submittedError=false;\n console.log(value);\n } else {\n this.submittedError=true;\n console.log('invalid form');\n }\n }\n}\n\n\ndemo",
2018-06-08T01:02:53
Hyuck Kang :

You have to use an extra flag to do that.\n\nLike below,\n\nsubmitted = false;\nonSubmit() { this.submitted = true; }\n\n\nAnd insert submitted into *ngIf statement.\n\nReference :\nhttps://angular.io/guide/forms#toggle-two-form-regions-extra-credit",
2018-06-08T01:04:44
yy