0

I have created an angular form that displays input validation errors received from the server. My solution works fine except for one small issue. If I submit the form with no value, after the page loads, I am receiving the correct response from my server i.e. 422, but the validation error is not displayed. If I then start typing a value in the input the validation error flashes and disappears.

I am almost certain that it has something to do with my directive, but I'm not sure how to fix it. This is my current directive code:

var appServices = angular.module('webFrontendApp.directives', []);

appServices.directive('serverError', function(){
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope,element,attrs,ctrl){
      element.on('change keyup', function(){
        scope.$apply(function(){
          ctrl.$setValidity('server', true);
        });
      });
    }
  };
});

I think the issue is with the element.on('change keyup'.... section of this code. That's why the error message flashes when I start typing. Also when I change this to 'change' instead of 'change keyup', the error message is displayed permanently when I start typing.

Does anybody have an idea of how I can display the error message even if I did not type any value into the input before submitting it the first time?

UPDATE AS PER COMMENT

Here is my form:

<form ng-submit="create(memberData)" name="form" novalidate>
  <div class = "row form-group" ng-class = "{ 'has-error' : form.email.$dirty && form.email.$invalid }">
     <input type="text" ng-model="memberData.email" placeholder="janedoe@mail.com"  name="email" class="col-xs-12 form-control" server-error>

     <span class="errors" ng-show="form.email.$dirty && form.email.$invalid">
       <span class="glyphicon glyphicon-remove form-control-feedback"></span>
       <span ng-show="form.email.$error.server">{{errors.email}}</span>
     </span>
  </div>
  <div class="row">
    <button type="submit" class="btn btn-danger col-xs-12">Join Private Beta</button>
  </div>
</form>

And my controller:

$scope.memberData = {};
$scope.create = function() {
    var error, success;
    $scope.errors = {};
    success = function() {
      $scope.memberData = {};
    };    
    error = function(result) {
        angular.forEach(result.data.errors, function(errors, field) {
            $scope.form[field].$setValidity('server', false);
            $scope.errors[field] = errors.join(', ');
        });    
    };



    BetaMember.save({ beta_member: { email: $scope.memberData.email || "" }}).$promise.then(success, error);

};
4

2 回答 2

0

由于表单本身没有 $setValidity 方法,因为没有 ng-model,并且假设服务器错误不涉及单个字段(在这种情况下,首选 $setValidity 方法),我认为最简单的解决方案可能是这个:

创建一个带有一些随机验证的表单(这个表单至少需要用户名)和一个可以显示自定义服务器错误的 div。

<div ng-controller="AppCtrl">

    <form novalidate name="createForm">

        <div class="inputWrap">

            <input ng-model="name" name="name" type="text" required placeholder="John Doe">

            <span ng-if="createForm.name.$dirty && createForm.name.$invalid">
                Some kind of error!
            </span>

        </div>

        <div ng-if="serverError">
            {{ serverError.message }}
        </div>

        <input
            value="Join Private Beta"
            ng-disabled="createForm.$invalid || serverError" 
            ng-click="create()"
            type="button">

    </form>

</div> 

然后在您的控制器中,您可以添加处理YourService的create方法(应该返回一个 promise ),如果响应失败,您可以创建一个带有自定义服务器错误消息的简单对象,该对象对于禁用表单按钮也很有用,如果你需要。

var AppCtrl = function($scope, YourService){

    // Properties

    // Shared Properties

    // Methods
    function initCtrl(){}

    // Shared Methods
    $scope.create = function(){

        YourService.makeCall().then(function(response){

            // Success!

            // Reset the custom error
            $scope.serverError = null;

        }, function(error){

            // Do your http call and then if there's an error
            // create the serverError object with a message
            $scope.serverError = {
                message : 'Some error message'
            };

        })

    };

    // Events

    // Init controller
    initCtrl();

};

AppCtrl.$inject = [
    '$scope',
    'YourService'
];

app.controller('AppCtrl', AppCtrl);

我的意思是这是非常简单的片段,我只是想举一个例子。没什么复杂的,但您可以将其扩展到更多内容。

于 2015-09-06T09:39:20.407 回答
0

似乎有一个非常简单的解决方法。由于我的视图中有过滤器 form.email.$dirty,因此如果用户单击提交而不先单击表单,则不会显示错误。

删除 form.email.$dirty 并且只有 form.email.$invalid 后,它可以完美运行。我认为这在我的情况下就足够了,因为此验证取决于服务器响应,并且不会在提交表单之前触发。错误对象也在我的控制器中被清除,确保页面在首次加载时不会加载错误。

于 2015-09-06T11:48:34.400 回答