本文介绍了AngularJS - 服务器端验证和客户端形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何做以下事情:

I am trying to understand how to do the following things:

什么是声明形式接受的方式。我的理解是,你只需要声明的HTML表单,并添加NG-模型的指令,像这样:

What is the accepted way of declaring a form. My understanding is you just declare the form in HTML, and add ng-model directives like so:

ng-model="item.name"

什么以发送到服务器。我可以只发送项对象到服务器JSON和跨preT它。然后我可以在对象进行验证。如果失败,我抛出一个JSON的错误,并发回究竟是什么?是否有这样做的一个公认的方式?我如何推动验证错误从服务器到客户端在一个不错的方式?

What to send to the server. I can just send the item object to the server as JSON, and interpret it. Then I can perform validation on object. If it fails, I throw a JSON error, and send back what exactly? Is there an accepted way of doing this? How do I push validation errors from the server to the client in a nice way?

我真的需要一个例子,但Angulars文档是pretty不难理解了。

I really need an example, but Angulars docs are pretty difficult to understand.

编辑:看来我措辞,我的问题不好

It seems I've phrased my question poorly.

我知道如何验证客户端,以及如何处理错误/成功的承诺回调。我想知道的,是捆绑服务器方的错误消息到客户的接受的方式。说我有一个用户名和密码注册表单。我不想轮询用户名的服务器,然后使用角来确定存在重复。我想要的用户名发送到服务器,验证具有相同名称不存在其他帐户,然后提交表单。如果出现错误,我怎么送回来?

I know how to validate client side, and how to handle error/success as promise callbacks. What I want to know, is the accepted way of bundling SERVER side error messages to the client. Say I have a username and password signup form. I don't want to poll the server for usernames and then use Angular to determine a duplicate exists. I want to send the username to the server, validate no other account exists with the same name, and then submit form. If an error occurs, how do I send it back?

有关数据推为与附加像这样的错误域(键和值)服务器是什么:

What about pushing the data to the server as is (keys and values) with an error field appended like so:

{
  ...data...

  "errors": [
    {
      "context": null,
      "message": "A detailed error message.",
      "exceptionName": null
    }
  ]
}

然后结合到DOM。

Then binding to the DOM.

推荐答案

我也一直在用这种事情玩弄最近,我已经怀孕了的。我认为它你需要什么。

I've also been playing around with this kind of thing recently and I've knocked up this demo. I think it does what you need.

设置窗体按正常与任何特定的客户端验证要使用:

Setup your form as per normal with any particular client side validations you want to use:

<div ng-controller="MyCtrl">
    <form name="myForm" onsubmit="return false;">
        <div>
            <input type="text" placeholder="First name" name="firstName" ng-model="firstName" required="true" />
            <span ng-show="myForm.firstName.$dirty && myForm.firstName.$error.required">You must enter a value here</span>
            <span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span>
        </div>
        <div>
            <input type="text" placeholder="Last name" name="lastName" ng-model="lastName"/>
            <span ng-show="myForm.lastName.$error.serverMessage">{{myForm.lastName.$error.serverMessage}}</span>
        </div>
        <button ng-click="submit()">Submit</button>
    </form>
</div>

请注意我还添加了一个 SERVERMESSAGE 每个字段:

Note also I have added a serverMessage for each field:

<span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span>

这是从服务器回来一个可定制的消息,它的工作原理相同的方式与任何其他错误信息(只要我可以告诉)。

This is a customisable message that comes back from the server and it works the same way as any other error message (as far as I can tell).

下面是控制器:

function MyCtrl($scope, $parse) {
      var pretendThisIsOnTheServerAndCalledViaAjax = function(){
          var fieldState = {firstName: 'VALID', lastName: 'VALID'};
          var allowedNames = ['Bob', 'Jill', 'Murray', 'Sally'];

          if (allowedNames.indexOf($scope.firstName) == -1) fieldState.firstName = 'Allowed values are: ' + allowedNames.join(',');
          if ($scope.lastName == $scope.firstName) fieldState.lastName = 'Your last name must be different from your first name';

          return fieldState;
      };
      $scope.submit = function(){
          var serverResponse = pretendThisIsOnTheServerAndCalledViaAjax();

          for (var fieldName in serverResponse) {
              var message = serverResponse[fieldName];
              var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage');

              if (message == 'VALID') {
                  $scope.myForm.$setValidity(fieldName, true, $scope.myForm);
                  serverMessage.assign($scope, undefined);
              }
              else {
                  $scope.myForm.$setValidity(fieldName, false, $scope.myForm);
                  serverMessage.assign($scope, serverResponse[fieldName]);
              }
          }
      };
}

我是pretending来调用 pretendThisIsOnTheServerAndCalledViaAjax 服务器你可以用一个Ajax调用替换它,关键是它只是返回验证状态每个字段。在这个简单的情况下,我使用值有效来表示该字段是有效的,任何其他值将被视为一个错误信息。您可能需要一些更复杂!

I am pretending to call the server in pretendThisIsOnTheServerAndCalledViaAjax you can replace it with an ajax call, the point is it just returns the validation state for each field. In this simple case I am using the value VALID to indicate that the field is valid, any other value is treated as an error message. You may want something more sophisticated!

一旦你从服务器验证状态,你只需要在你的形式来更新状态。

Once you have the validation state from the server you just need to update the state in your form.

您可以从范围内访问的形式,在这种情况下,形式称为 myForm会因此$ scope.myForm让你的形式。 (图片来源为,如果你想它是如何工作的读了)。

You can access the form from scope, in this case the form is called myForm so $scope.myForm gets you the form. (Source for the form controller is here if you want to read up on how it works).

您再要告诉表单字段是否有效/无效:

You then want to tell the form whether the field is valid/invalid:

$scope.myForm.$setValidity(fieldName, true, $scope.myForm);

$scope.myForm.$setValidity(fieldName, false, $scope.myForm);

我们还需要设置错误消息。首先,获得使用$解析领域的访问。然后分配来自服务器的值

We also need to set the error message. First of all get the accessor for the field using $parse. Then assign the value from the server.

var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage');
serverMessage.assign($scope, serverResponse[fieldName]);

希望帮助

这篇关于AngularJS - 服务器端验证和客户端形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 10:01