How to display server errors in Angularjs with ng-messages

后端 未结 4 1882
情话喂你
情话喂你 2021-02-02 10:30

I have have my angular app validating a sign-up form. On submit, the server also validates the data. I\'m outputting error messages in angular using ng-messages.

Here i

4条回答
  •  梦如初夏
    2021-02-02 10:45

    Well, this is not the most elegant solution since you really should leverage the asyncValidators in angular 1.3.x and then create your custom validation directives.

    Resources

    http://plnkr.co/edit/s4jJAOqehBkFUC9osMsy?p=preview found in the post by this guy.

    Possibly here http://odetocode.com/blogs/scott/archive/2014/10/16/working-with-validators-and-messages-in-angularjs.aspx

    And of course in the docs

    But be cautious as this is not in any way a complete example ready to be used. It's mostly here for demo purpose and to sort of give you an idea where to start. I have not bothered with clearing any previous errors, revalidating the form or taken into account other validation errors.

    Awesomeness

    Imagine your controller looks like this

    $scope.serverValidations = {};
    $scope.attemptSignUp = function(){
    
        Api.validateEmail($scope.email).then(angular.noop, function(data){
    
          $scope.serverValidations = data
          for(prop in $scope.serverValidations){
              if($scope.signUpForm[prop]){
                angular.forEach($scope.serverValidations[prop],function(validation){
                    $scope.signUpForm[prop].$setValidity(validation.type, false);
                });
              }
          }
        });
    }
    

    and your response data containing validation errors look like this

    {
      email:[
         {type:'unique', message:'This email is already in use'}
      ],
      name:[
         {type:'maxlength', message:'Your name is to long, get a new one :)'}
      ]
    };
    

    Then in your HTML you could do like this

    You don't have a name?

    {{validation.message}}

    Here's a dirty Codepen for you: http://codepen.io/anon/pen/yyzMgG?editors=101 When you press submit, after 2 seconds (the time it takes to hit the fake server) your server validations are presented.

提交回复
热议问题