0
votes

I am using Angular JS 1.5.11.

I have a form with error messages and styling on my fields. I have found information on how to trigger the validation on blur, debounce, etc.

But I also want the fields to be checked when the form is submitted. I have found info on how to tell if the form is valid on submit and then process the form -- just not how to active the field error messages when the user submits.

To clarify: I have error message on my fields. When the user submits, if there are errors on field(s) I want the error messages to appear (and the user must fix the errors and re-submit).

I have something like this:

 <form name="abc.myForm" class="spacer-top-md" ng-submit="abc.save(abc.user)" novalidate>

 <div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && !myForm.name.$pristine }">
  <label>Name</label>
  <input type="text" name="name" class="form-control" ng-model="abc.user.name" ng-model-options="{ updateOn: 'blur'}" required>
  <p ng-show="myForm.name.$invalid && !myForm.name.$pristine" class="help-block">Enter your name.</p>
</div>

<input type="submit" class="btn btn-primary">

And in my controller:

  _this.master = {};

  _this.save = function (user) {
    _this.master = angular.copy(user);
  };

  _this.reset = function () {
    _this.user = angular.copy(_this.master);
  };

  _this.reset();

The submit works, the data is copied from the user object to the master object. But if there are empty fields, no errors. The only way to trigger errors so far is to enter data into the fields and tab out.

2
probably update required for ng-required="true" - Matej Marconak

2 Answers

0
votes

You can use

   myForm.$submitted && myForm.email.$error.required

OR, alternatively:

 <form name="form" ng-app>
 <div class="control-group" ng-class="{true: 'error'}[submitted &&      form.email.$invalid]">
    <label class="control-label" for="email">Your email address</label>
    <div class="controls">
        <input type="email" name="email" ng-model="email" required />
        <span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
        <span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
    </div>
</div>

<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>

0
votes

You should include ng-messages directive to your app,

here is snippet what you should add to your html, to use ng-messages directive.

'required' attribute in input element will be watched by directive and triger messages.

Don't forget for dependency injection in module.

<div ng-messages="abc.myForm.name.$error" ng-show="abc.myForm.name.$touched">
                <p ng-message="required">This field is required.</p>
            </div>