我有一个表单的输入字段和验证设置通过添加所需的属性等。但对于某些字段,我需要做一些额外的验证。我如何“输入”到FormController控制的验证?
自定义验证可以是类似于“如果这3个字段被填写,那么这个字段是必需的,需要以特定的方式格式化”。
FormController中有一个方法。$setValidity,但这看起来不像一个公共API,所以我宁愿不使用它。创建一个自定义指令并使用NgModelController看起来是另一种选择,但基本上需要我为每个自定义验证规则创建一个指令,这是我不想要的。
实际上,从控制器标记字段为无效(同时也保持FormController同步)可能是我在最简单的场景中需要完成的工作,但我不知道如何做到这一点。
这里有一个很酷的方法来在一个表单中进行自定义通配符表达式验证(来自:AngularJS和过滤器的高级表单验证):
<form novalidate="">
<input type="text" id="name" name="name" ng-model="newPerson.name"
ensure-expression="(persons | filter:{name: newPerson.name}:true).length !== 1">
<!-- or in your case:-->
<input type="text" id="fruitName" name="fruitName" ng-model="data.fruitName"
ensure-expression="(blacklist | filter:{fruitName: data.fruitName}:true).length !== 1">
</form>
app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ngModelController) {
scope.$watch(attrs.ngModel, function(value) {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelController.$setValidity('expression', booleanResult);
});
}
};
}]);
jsFiddle演示(支持表达式命名和多个表达式)
它类似于ui-validate,但你不需要特定于作用域的验证函数(这是通用的),当然你也不需要ui。Utils这样。
调用服务器的自定义验证
使用ngModelController $asyncValidators API来处理异步验证,比如向后端发送$http请求。添加到对象中的函数必须返回一个promise,该promise在有效时必须被解析,在无效时必须被拒绝。正在进行的异步验证通过key存储在ngModelController.$pending中。更多信息请参见AngularJS开发者指南-表单(自定义验证)。
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
有关更多信息,请参见
ngModelController $asyncValidators API
AngularJS开发者指南-表单(自定义验证)。
使用$validators API
接受的答案使用$parsers和$formatters管道添加一个自定义同步验证器。AngularJS 1.3+添加了一个$validators API,这样就不需要在$parsers和$formatters管道中添加验证器了:
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$validators.blacklist = function(modelValue, viewValue) {
var blacklist = attr.blacklist.split(',');
var value = modelValue || viewValue;
var valid = blacklist.indexOf(value) === -1;
return valid;
});
}
};
});
更多信息请参见AngularJS ngModelController API Reference - $validators。
在AngularJS中,定义自定义验证的最佳位置是Cutsom指令。
AngularJS提供了一个ngMessages模块。
ngMessages是一个用来显示和隐藏消息的指令
基于所监听的键/值对象的状态。的
指令本身补充了ngModel的错误消息报告
$error对象(存储验证错误的键/值状态)。
对于自定义表单验证,应该使用带有自定义指令的ngMessages模块。这里我有一个简单的验证,它将检查数字长度是否小于6在屏幕上显示错误
<form name="myform" novalidate>
<table>
<tr>
<td><input name='test' type='text' required ng-model='test' custom-validation></td>
<td ng-messages="myform.test.$error"><span ng-message="invalidshrt">Too Short</span></td>
</tr>
</table>
</form>
下面是如何创建自定义验证指令
angular.module('myApp',['ngMessages']);
angular.module('myApp',['ngMessages']).directive('customValidation',function(){
return{
restrict:'A',
require: 'ngModel',
link:function (scope, element, attr, ctrl) {// 4th argument contain model information
function validationError(value) // you can use any function and parameter name
{
if (value.length > 6) // if model length is greater then 6 it is valide state
{
ctrl.$setValidity('invalidshrt',true);
}
else
{
ctrl.$setValidity('invalidshrt',false) //if less then 6 is invalide
}
return value; //return to display error
}
ctrl.$parsers.push(validationError); //parsers change how view values will be saved in the model
}
};
});
$setValidity是一个内置函数,用于设置模型状态为有效/无效
我最近创建了一个指令,允许基于表达式的角表单输入失效。任何有效的角表达式都可以使用,并且它支持使用对象表示法自定义验证键。用angular v1.3.8测试
.directive('invalidIf', [function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var argsObject = scope.$eval(attrs.invalidIf);
if (!angular.isObject(argsObject)) {
argsObject = { invalidIf: attrs.invalidIf };
}
for (var validationKey in argsObject) {
scope.$watch(argsObject[validationKey], function (newVal) {
ctrl.$setValidity(validationKey, !newVal);
});
}
}
};
}]);
你可以这样使用它:
<input ng-model="foo" invalid-if="{fooIsGreaterThanBar: 'foo > bar',
fooEqualsSomeFuncResult: 'foo == someFuncResult()'}/>
或者通过传入一个表达式(它将被赋予默认的validationKey " invalididif ")
<input ng-model="foo" invalid-if="foo > bar"/>