Using angular 1.3 ngMessage for form submission errors

I have an example of form validation in my application for a login page, looking something like this:

 <div class="form-group" >
            <label for="password">Password</label>
            <input type="password"
                   id="password"
                   name="password"
                   class="form-control"
                   placeholder="Create password"
                   ng-model="password"
                   required
                   minlength="{{passwordLength}}"
                   >
            <div class="help-block text-danger"
                 ng-messages="form.password.$error"
                 ng-if="form.password.$touched || form.$submitted"
                 >
              <div class="text-danger">
                <div ng-message="required">A password is required</div>
                <div ng-message="minlength" >Password must be at least {{passwordLength}} characters</div>
              </div>

            </div>
          </div>

      

This is great for "required" and "minimum" checks that can be performed prior to submission. However, after submitting, we may return a 401 for an incorrect username / password. Angular 1.3 has the concept of async validaiton, but it seems to run before submitting and it seems unreasonable to try to login twice (once to see if they might and throw an error).

Is there a sane way to use the concept of ng-messages to display this error after submitting?

+3


source to share


1 answer


I understood that. You can simply manually submit / cancel the form:

<div class="help-block text-danger">
            <div class="text-danger"
                 ng-messages="form.password.$error"
                 ng-if="form.password.$touched || form.$submitted">
              <div ng-message="required">Password is required</div>
              <div ng-message="minlength">*Password must be at least {{passwordLength}} characters</div>
              <div ng-message="correctPassword">Username/Password combination is incorrect</div>
            </div>
          </div>

      



and in your controller, send:

 $scope.login = function(){
    $scope.form.password.$setValidity("correctPassword", true);
    // ...do some stuff...
    $http.post('/someUrl', {msg:'hello word!'})
      .success(function(){})
      .error(function() {
         $scope.form.password.$setValidity("correctPassword", false);
  });
 }

      

+6


source







All Articles