我正在创建一个远程验证指令,它允许我检查我的服务器是否验证了该字段。
到目前为止我有这个:
angular.module('Form').directive('remoteFieldValidation', function (Query) {
return {
restrict: 'A',
scope: {
fieldValue: '=ngModel'
},
link: function (scope, element, attr) {
element.parent().addClass('has-feedback');
element.focusout(function (value) {
var value = scope.fieldValue;
var checker = attr.remoteFieldValidation;
if (value && checker) {
element.parent().append('<span class="form-control-feedback fa fa-spinner fa-spin" style="line-height: 35px"></span>');
Query.api2({
method: 'GET',
route: 'validateField',
params: {
value: value,
checker: checker
}
}).then(function (result) {
})
}
else {
console.log('Missing checker or value');
}
})
}
}
});
为了清除,Query 是我自己的 API 服务,基本上它控制 $http 请求
。
现在,当我将此属性指令添加到输入字段时,我想确保一旦开始验证,它就会将表单设置为无效。
但是我不太确定如何从该指令访问表单。
有谁知道我该如何执行此操作以防止用户在检查远程验证之前提交表单?
最佳答案
您可以通过静态方式执行此操作,只需让提交操作等待服务器验证您的字段即可。然而,更好的方法是添加 $asyncValidator
在您的 ngModel 上。这是 AngularJs 1.3 版本中引入的功能。
通过使用此解决方案,您将能够使用 Angular 形式属性捕获验证错误:
<div ng-show="form.myField.$error.myRemoteValidator">The value is not valid!</div>
或者使用ngMessages
像这样:
<div ng-messages="form.myField.$error">
<div ng-message="myRemoteValidator">The value is not valid!</div>
</div>
您的指令如下所示:
angular.module('Form')
.directive('remoteFieldValidation', function(Query, $q) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
ngModelCtrl.$asyncValidators
.myRemoteValidator = function(modelValue, viewValue) {
var value = modelValue || viewValue;
var checker = attr.remoteFieldValidation;
return Query.api2({
method: 'GET',
route: 'validateField',
params: {
value: value,
checker: checker
}
}).then(function(result) {
if (result.isValid) {
// it says to validator that it's valid
return true;
} else {
// it says to validator that it's not valid
// and also send the error message
return $q.reject('Invalid field');
}
}, $q.reject); // invalidate in case of any errors on your api or request
};
}
}
});
更新
示例:
<form name="form">
...
<input type="text" ng-model="myField" remote-field-validation>
<div ng-messages="form.myField.$error">
<div ng-message="myRemoteValidator">The value is not valid!</div>
</div>
...
<button ng-disabled="form.$invalid">Save</button>
</form>
关于javascript - 如何创建指令来远程验证表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358163/