本文介绍了AngularJS - 服务器端验证和客户端表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图了解如何做以下事情:
公认的表单声明方式是什么.我的理解是您只需在 HTML 中声明表单,然后添加 ng-model 指令,如下所示:
ng-model="item.name"
要发送到服务器的内容.我可以将 item 对象作为 JSON 发送到服务器,并对其进行解释.然后我可以对对象执行验证.如果失败,我会抛出一个 JSON 错误,然后发回究竟是什么?有没有一种可接受的方式来做到这一点?如何以一种不错的方式将验证错误从服务器推送到客户端?
我真的需要一个例子,但 Angulars 文档很难理解.
看来我的问题措辞不当.
我知道如何验证客户端,以及如何将错误/成功作为承诺回调处理.我想知道的是将 SERVER 端错误消息捆绑到客户端的可接受方式.假设我有一个用户名和密码注册表单.我不想轮询服务器以获取用户名,然后使用 Angular 来确定是否存在重复项.我想将用户名发送到服务器,验证不存在同名的其他帐户,然后提交表单.如果发生错误,我如何将其发回?
如何将数据按原样(键和值)推送到服务器,并像这样附加错误字段:
{...数据...错误":[{上下文":空,"message": "详细的错误信息.",异常名称":空}]}
然后绑定到 DOM.
解决方案
我最近也一直在玩这种东西,我敲了敲这个演示.我认为它可以满足您的需求.
使用您要使用的任何特定客户端验证按照正常方式设置您的表单:
<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">您必须在此处输入一个值</span><span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span>
<div><input type="text" placeholder="Last name" name="lastName" ng-model="lastName"/><span ng-show="myForm.lastName.$error.serverMessage">{{myForm.lastName.$error.serverMessage}}</span>
<button ng-click="submit()">提交</button></表单>
请注意,我还为每个字段添加了一个 serverMessage
:
<span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span>
这是一条从服务器返回的可自定义消息,它的工作方式与任何其他错误消息相同(据我所知).
这是控制器:
function MyCtrl($scope, $parse) {var假装ThisIsOnTheServerAndCalledViaAjax = function(){var fieldState = {firstName: 'VALID', lastName: 'VALID'};var allowedNames = ['Bob', 'Jill', 'Murray', 'Sally'];if (allowedNames.indexOf($scope.firstName) == -1) fieldState.firstName = '允许的值为:' + allowedNames.join(',');if ($scope.lastName == $scope.firstName) fieldState.lastName = '您的姓氏必须与您的名字不同';返回字段状态;};$scope.submit = function(){var serverResponse = 假装ThisIsOnTheServerAndCalledViaAjax();for (var fieldName in serverResponse) {var message = serverResponse[fieldName];var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage');如果(消息=='有效'){$scope.myForm.$setValidity(fieldName, true, $scope.myForm);serverMessage.assign($scope, undefined);}别的 {$scope.myForm.$setValidity(fieldName, false, $scope.myForm);serverMessage.assign($scope, serverResponse[fieldName]);}}};}
我假装在 pretendThisIsOnTheServerAndCalledViaAjax
中调用服务器,您可以将其替换为 ajax 调用,重点是它只返回每个字段的验证状态.在这个简单的例子中,我使用值 VALID
来指示该字段是有效的,任何其他值都被视为错误消息.你可能想要更复杂的东西!
从服务器获得验证状态后,您只需要更新表单中的状态.
您可以从范围访问表单,在这种情况下,表单称为 myForm
,因此 $scope.myForm 为您获取表单.(表单控制器的来源如果你想阅读它是如何工作的).
然后您想告诉表单该字段是否有效/无效:
$scope.myForm.$setValidity(fieldName, true, $scope.myForm);
或
$scope.myForm.$setValidity(fieldName, false, $scope.myForm);
我们还需要设置错误信息.首先使用 $parse 获取字段的访问器.然后从服务器分配值.
var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage');serverMessage.assign($scope, serverResponse[fieldName]);
希望有帮助
I am trying to understand how to do the following things:
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"
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?
I really need an example, but Angulars docs are pretty difficult to understand.
Edit: 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
}
]
}
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>
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).
Here is the controller:
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]);
}
}
};
}
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.
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);
or
$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]);
Hope that helps
这篇关于AngularJS - 服务器端验证和客户端表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!