0

I have angular validation and server side validation (like username taken). I am binding server errors to form elements.

$scope.registerFormSubmit = function()
{
    if (isEmpty($scope.registerForm.$error))
    {
        $http({
            url: '/profile/register',
            method: 'POST',
            dataType: 'json',
            data: toArray($scope.form),
        }).error(function(response){
            if (false == is(response.formErrors)) return;
            for (var k in $scope.registerForm)
            {
                if (!is(response.formErrors[k]))
                {
                    try
                    {
                        $scope.registerForm[k].$error = {};
                    }catch(e){

                    }

                    continue;
                }
                else
                {
                    $scope.registerForm[k].$error[response.formErrors[k]] = 1;
                }
            }

        });
    }
}

The problem is when user change model (ex. username) errors from server still exists after submit clicked. So, ajax can't be send because condition

isEmpty($scope.registerForm.$error)

Is always false because form has errors.

1 Answer 1

0

There's a pretty comprehensive discussion of using Angular with server side validation here: AngularJS: integrating with server-side validation

A lighter-weight solution I've used:

  • Key the errors so you know they're a server error. To preserve knowledge of the specific error, you could do something like this instead in your current error handler:

$scope.registerForm[k].$error.server = 'Error-specific string. Could also be an object';

  • Clear the server errors on input change. Here's a sample directive to do it on keydown:

angular.module('myApp')
  .directive('serverError', function () {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        element.on('keydown', function() {
          return ngModel.$setValidity('server', true);
        });
      }
    };
  });
<input type="text" ng-model="username" placeholder="coolguy" server-error />

  • Then you can just apply the server-error directive to all your form elements.
Sign up to request clarification or add additional context in comments.

Comments

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.