gpt4 book ai didi

angularjs - 是否可以在 Angular 字段上拥有多个自定义验证器?

转载 作者:行者123 更新时间:2023-12-01 00:56:07 24 4
gpt4 key购买 nike

我试过这个代码:

   .directive('uniqueUsername', function (isUsernameAvailable) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$asyncValidators.uniqueName = isUsernameAvailable;
}
};
})
.directive("isMinSix", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.isMinSix = function (modelValue) {
if (modelValue != null && modelValue.length < 6) {
return true;
} else {
return false;
}
}
}
}
})
.factory('isUsernameAvailable', function (appConstant, $q, $http) {
return function (username) {
var deferred = $q.defer();
var url = appConstant.baseUrl + '/api/user/existsByName';
$http({
url: url,
method: "PUT",
data: {
userName: username
}
}).then(function () {
// Found the user, therefore not unique.
deferred.reject("User name is taken");
}, function () {
// User not found, therefore unique!
deferred.resolve();
});
return deferred.promise;
}
})

我的问题是,当我仅将这两个指令添加到一个输入,然后在检查中放置一个调试点时,只有一个或另一个会触发。我无法让它们同时正常工作:
                <input class="inputField"
id="registerUserName"
name="registerUserName"
is-min-six
ng-model="aus.registerUserName"
ng-model-options="{ debounce: 3000 }"
ng-required="true"
placeholder="Username"
type="text"
unique-username
value="" />

有没有人知道我可能做错了什么?

最佳答案

可以有多个验证器,但异步验证器只有在同步验证器通过后才会运行。这可以在 documentation 中找到和 source code :

Also, all asynchronous validators will only run once all synchronous validators have passed.



这是有道理的,因为异步验证器很可能是远程过程,如果该字段无论如何无效,这将是浪费的。当然,可以修改上面链接的源代码以使其以您的首选方式工作,这似乎是始终运行异步验证器。

关于angularjs - 是否可以在 Angular 字段上拥有多个自定义验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820453/

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