13

The default validation for the form I have works as expected. But when a user types in a valid email address and a password of three characters minimum, that doesn't mean the login credentials are valid.

So my question is:

How can I set the model email and password to invalid after server-side validation, so the input-fields get the class ng-invalid instead of ng-valid.

My current code

function IndexCtrl( $scope, $http )
{
  $scope.form = {};
  $scope.submitLogin = function ()
  {
    $http.post( '/api/auth/login', $scope.form ).success( function( data )
    {
      if ( !data.success )
      {
        $scope.form.errors = [ data ];

        // here I also want to mark the models 'email' and 'password' as invalid, so they both get the class 'ng-invalid'
      }
      else
      {
        $location.path( '/' );
      }
    });
  };
}
2
  • 4
    Can you simply use $setValidity method? Commented Aug 28, 2012 at 21:43
  • 2
    Totally unrelated, but I set status code to 400 when my AJAX calls return errors. This way you don't need to check or set data.success but instead just handle errors in the error callback. Commented Mar 20, 2013 at 9:28

4 Answers 4

5

Tosh shimayama gave the right answer. $setValidity is a method from the NgModelController and takes two parameters: validationErrorKey and isValid.

More information on $setValidity

Change the validity state, and notifies the form when the control changes validity. (i.e. it does not notify form if given validator is already marked as invalid).

Source and further information AngularJS: NgModelController

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

Comments

3

Client-side validation is quick, but it is easy to break, using for example - firebug. You can stick with only server-side validation. Validate everything on server and return BODY with list of keys and error messages. Angular allows you to send data to server asynchronously, end user will see it as client-side validation, as there was no visible post-back.

See this example, try to click 'Save', and see error messages: upida.cloudapp.net:8080/org.upida.example.angular/order/create?clientId=1

You can download it: upida.codeplex.com

Comments

0

Here is a nice validation directive that might be usefull https://groups.google.com/forum/#!msg/angular/6v-AillQboI/D0OaZzV7Me0J

Comments

0

I done something but its rails specific, maybe it could give someone an idea, or push in the right direction https://github.com/fmatosic/bubblemevalid

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.