Search code examples
angularjsformsvalidationserver-side

AngularJS - How to set validity true after change the field


I've followed this answer to run custom server side validation for unique email constraint.

This is my submit function on controller:

function submit(form){
  CompanyUser.save(vm.model)
      .success(function(data) {
          vm.closeModal();
          toastSucess(data);
      })
      .error(function(data) {
          if(data.code == 'error_duplicated_email')
              form['email'].$setValidity("uniqueEmail", false);
      });

}

and here my email piece of HTML code:

<form name="form" novalidate ng-click="form.$valid && vm.submit(form)">
    <div class="form-group" ng-class="{ 'has-error': form.$submitted && form.email.$error.uniqueEmail }">
        <label>E-mail</label>
        <input type="email" class="form-control" name="email" ng-model="vm.model.email" required>
        <span ng-show="form.$submitted && form.email.$error.uniqueEmail" class="help-block">Duplicated e-mail</span>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-white" ng-click="vm.closeModal()">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
</form>

And works fine once that server returns the error. But, then I change the email and try to submit, but I cannot do it anymore. I think that is because I've set the validity to false. So how can I set to true to try to submit the form again?


Solution

  • Here is the solution from @code90:

    I needed to add a ng-change="form.$valid=true" to the <input type="email"..

    and it works fine!