krynio
krynio

Reputation: 2492

Server side validation for multiple fields in Angular

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/

Upvotes: 1

Views: 289

Answers (1)

adolfosrs
adolfosrs

Reputation: 9389

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

Upvotes: 1

Related Questions