gpt4 book ai didi

validation - AngularJS:与服务器端验证集成

转载 作者:行者123 更新时间:2023-12-03 05:51:14 25 4
gpt4 key购买 nike

我有一个 Angular 应用程序,其中包含一个取自示例的保存按钮:

<button ng-click="save" ng-disabled="form.$invalid">SAVE</button>

这对于客户端验证非常有用,因为当用户修复问题时,form.$invalid 会变为 false,但如果另一个用户使用同一电子邮件注册,我有一个电子邮件字段将设置为无效。

一旦我将电子邮件字段设置为无效,我就无法提交表单,并且用户无法修复该验证错误。所以现在我不能再使用 form.$invalid 来禁用我的提交按钮。

一定有更好的方法

最佳答案

这是自定义指令成为您 friend 的另一种情况。您需要创建一个指令并将 $http 或 $resource 注入(inject)其中,以便在验证时回调服务器。

自定义指令的一些伪代码:

app.directive('uniqueEmail', function($http) {
var toId;
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the email.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);

// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/Is/My/EmailValid?email=' + value).success(function(data) {

//set the validity of the field
ctrl.$setValidity('uniqueEmail', data.isValid);
});
}, 200);
})
}
}
});

以下是在标记中使用它的方法:

<input type="email" ng-model="userEmail" name="userEmail" required unique-email/>
<span ng-show="myFormName.userEmail.$error.uniqueEmail">Email is not unique.</span>

编辑:对上面发生的事情的一个小解释。

  1. 当您更新输入中的值时,它会更新 $scope.userEmail
  2. 该指令在其链接函数中设置了 $scope.userEmail 上的 $watch。
    • 当 $watch 被触发时,它会通过 $http ajax 调用来调用服务器,并传递电子邮件
    • 服务器将检查电子邮件地址并返回一个简单的响应,例如“{ isValid: true }
    • 该响应用于控件的 $setValidity。
  3. 标记中的 ng-show 设置为仅在 uniqueEmail 有效性状态为 false 时显示。

...对于用户来说意味着:

  1. 输入电子邮件地址。
  2. 稍微停顿。
  3. 如果电子邮件不唯一,“电子邮件不唯一”消息将显示“实时”。

EDIT2:这也允许您使用 form.$invalid 禁用提交按钮。

关于validation - AngularJS:与服务器端验证集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12864887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com