show validation error messages on submit in angularjs

Gihan picture Gihan · Sep 14, 2013 · Viewed 218.5k times · Source

I have a form which need to show validation error messages if clicked submit.

Here is a working plunker

 <form name="frmRegister" ng-submit="register();" novalidate>
      <div>
        <input placeholder="First Name" name="first_name" type="text" ng-model="user.firstName" required />
        <span ng-show="frmRegister.first_name.$dirty && frmRegister.first_name.$error.required">First Name is required</span>
      </div>
      <div>
        <input placeholder="Last Name" name="last_name" type="text" ng-model="user.lastName" required />
        <span ng-show="frmRegister.last_name.$dirty && frmRegister.last_name.$error.required">Last Name is required</span>
      </div>
      <div>
        <input placeholder="Email" name="email" type="email" ng-model="user.email" required />
        <span ng-show="frmRegister.email.$dirty && frmRegister.email.$error.required">Email is required.</span>
        <span ng-show="frmRegister.email.$dirty && frmRegister.email.$error.email">Invalid Email address.</span>
      </div>
      <input type="submit" value="Save" />
      <span ng-show="registered">YOU ARE NOW REGISTERED USER</span>
 </form>

Validation works normally when user start making changes. But it doesn't show any error messages If clicked submit without entering anything.

Any thought of achieving this?. Or in other way how can I make each input field $dirty when clicks the Submit button

Answer

Chandermani picture Chandermani · Sep 14, 2013

I found this fiddle http://jsfiddle.net/thomporter/ANxmv/2/ which does a nifty trick to cause control validation.

Basically it declares a scope member submitted and sets it true when you click submit. The model error binding use this extra expression to show the error message like

submitted && form.email.$error.required

UPDATE

As pointed out in @Hafez's comment (give him some upvotes!), the Angular 1.3+ solution is simply:

form.$submitted && form.email.$error.required