1

I have form where I need validation on server side. Backend use one request to validate multiple fields. I try to add validation message after response. Here is example:

This is my html code:

<div ng-app="MyApp">
  <div ng-controller="MyController">
    <form name="MyForm" novalidate ng-submit="send()">
      <div>
        <label>Email</label>
        <input type="email" name="email" ng-model="user.email" required>
        <div ng-show="MyForm.email.$invalid">error message</div>
      </div>
      <input type="submit" ng-disabled="MyForm.$invalid">
      <pre>{{ MyForm.email.$error | json }}</pre>
    </form>
  </div>
</div>

And my js code:

var myApp = angular.module('MyApp', []);

myApp.controller("MyController", ['$scope', '$timeout', '$log', function($scope, $timeout, $log) {
    $scope.user = { "email" : "" }
  $scope.send = function() {
    $timeout(function() {
        $log.log("Response from server. Multiple fields validation.");
        $scope.MyForm["email"].$setValidity("server-side-error", false, $scope.MyForm)
        // here I want to add something what listen once on $scope.MyForm["email"] changed
    }, 1000);
  };
}]);

But I need remove error when value changed. How to achieve it using Angular?

Here is example: https://jsfiddle.net/9wqhd89z/

1
  • let me know if my answer works for you or if you still have any doubt. :) Commented Jun 26, 2016 at 22:12

1 Answer 1

1

You can call a check function whenever the user change the input using ng-change. So it will check if the email is currently invalid, and if it is it will set as valid again.

<input type="email" name="email" ng-model="user.email" ng-change="check()" required>

$scope.check = function(){
    if ($scope.MyForm.email.$valid == false){
        $scope.MyForm.email.$setValidity('server-side-error', true);
    }
}

You can find a working version in this jsFiddle

Sign up to request clarification or add additional context in comments.

2 Comments

It works, but I have another question. Errors could be dynamic and I wasn't to write check function for each input, but write one universal function which handle all server side errors. Is it possible?
You can work setting validity on $scope.MyForm.$setValidity. Then you can just go with $scope.MyForm.$setValidity('email-in-use-error', false). Only problem is that you wont be able to know what input is invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.