【发布时间】:2014-08-13 04:46:32
【问题描述】:
我需要创建一个验证指令来自动显示每个输入的所有输入错误。 此验证指令应显示当前的所有错误,并且应在用户键入时自动更新错误列表。
如果输入是脏的、非空的和无效的,我需要显示输入的所有错误。我需要将所有错误添加到此输入元素附近的 html 元素中。
例如,如果输入有 type="email" 和 ng-minlength="5" 并且用户输入了 'abc',我需要在此输入附近显示此类错误:'Invalid email;请输入至少 5 个字符;'
例如,如果输入的 type="number" attr 和 min="200" 和 min-model="minnumber" 和 minnumber 模型设置为 '300' 并且用户输入了 '100' 我需要在此附近显示此类错误input: '请输入最小数量500;应该大于 Min Number;'
如果相关模型(最小模型参数)更新,我还需要更新上一个示例中输入的所有错误消息。
var app = angular.module('app', []);
app.controller('appCtrl', function ($scope) {
});
app.directive('validate', function () {
return {
restrict: 'A',
require: 'ngModel', // require: '^form',
link: function (scope, element, attrs, ctrl) {
console.log('======================');
console.log(scope);
console.log(element);
console.log(attrs);
console.log(ctrl);
console.log(scope.form.$error);
angular.forEach(scope.form.$error, function (value, key) {
console.log('scope.form.$error = ' + key + ': ' + value);
console.log(value);
});
}
};
});
app.directive('positiveInteger', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var INTEGER_REGEXP = /^\d+$/;
if (INTEGER_REGEXP.test(viewValue)) { // it is valid
ctrl.$setValidity('positiveInteger', true);
return viewValue;
} else { // it is invalid, return undefined (no model update)
ctrl.$setValidity('positiveInteger', false);
return undefined;
}
});
}
};
});
app.directive('positiveFloat', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var FLOAT_REGEXP = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;
if (FLOAT_REGEXP.test(viewValue)) { // it is valid
ctrl.$setValidity('positiveInteger', true);
return viewValue;
} else { // it is invalid, return undefined (no model update)
ctrl.$setValidity('positiveInteger', false);
return undefined;
}
});
}
};
});
app.directive('minModel', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (viewValue > scope[attrs.minModel]) { // it is valid
ctrl.$setValidity('minModel', true);
return viewValue;
} else { // it is invalid, return undefined (no model update)
ctrl.$setValidity('minModel', false);
return undefined;
}
});
}
};
});
您能帮忙制定这个验证指令吗?
或者你能指出我正确的方向吗?
Link to JSFiddle with some code for testing.
附: UI-Utils 也有类似的东西,但他们的指令不能在一个地方设置类似的错误消息。
【问题讨论】:
-
这正是我创建这个开源模块jonsamwell.github.io/angular-auto-validate 的原因,它背后的原因在我的博文jonsamwell.com/dynamic-angularjs-validation
标签: javascript angularjs validation angularjs-directive