gpt4 book ai didi

javascript - AngularJS 表单的服务器端验证,在 View Controller 中使用 $setValidity 吗?

转载 作者:行者123 更新时间:2023-12-03 10:00:51 26 4
gpt4 key购买 nike

或者输入 tl;dr 代码:

form.email.$setValidity('冲突', false);

对于我的简单服务器端验证流程来说太粘了。

我正在尝试让表单在用户输入已被其他客户使用的电子邮件地址时显示良好的反馈。我正在运行 AngularJS v1.2 并有这个模板:

<form name="form">
<input name="email" type="email" ng-model="..." required>
</form>
<div ng-messages="form.email.$error">
<div ng-message="conflict">Email address already in use.</div>
</div>

在我的 Controller 中,我将处理提交事件并在我的 $http.post().error 处理程序中触发验证,如下所示:

$http.post('api/form/submit/path/here').error(function(resp) {
if (resp.details === 'conflict')
$scope.form.email.$setValidity('conflict', false);
});

问题是,当用户返回并更改输入字段中的值时,错误消息不会消失。它会一直存在,直到我手动调用 $scope.form.setValidity();

文档说使用 ng-model 依赖项实现自定义指令,但这对于我的目的来说似乎 super 大材小用。我还尝试设置 $scope.form.email.$valid = false;$scope.form.email.$invalid = true; 但那些没有更改文本框的外观。

最佳答案

代码中的任何内容都不会修改 conflict 验证 key ,除非显式调用 $setValidity('conflict', false) 时。由于这是设置冲突验证键状态的唯一代码,并且没有其他代码将其重置为 true,因此编辑文本框不会重置其冲突是预期的行为> 验证状态。

要获得您想要的行为,您需要为其编写代码。一种方法是使用 ng-change

<input name="email" type="email" ng-model="..." required ng-change="resetConflictState()">

$scope.resetConflictState = function() {
$scope.form.email.$setValidity('conflict', true);
}

关于javascript - AngularJS 表单的服务器端验证,在 View Controller 中使用 $setValidity 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30606770/

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