[英]Using element.bind in validation directive
I trying to validate input with custom directive: 我尝试使用自定义指令验证输入:
.directive('customValidation', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
element.bind("keydown keypress", function (event) {
if (!(event.keyCode >= 48 && event.keyCode <= 57)) {
return undefined;
}
})
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
but it doesn't work. 但这不起作用。 Any character is passes validation.
任何字符都通过验证。 What I doing wrong?
我做错了什么?
So basically what you are trying to achieve is to check if an input contains only numbers. 因此,基本上,您想要实现的是检查输入是否仅包含数字。 At least that is what I can understand from your explanation and the sample code.
至少从您的解释和示例代码中我可以理解。
First, you are using a parser
, which are used for sanitizing and converting values passed from the DOM to the model. 首先,您使用
parser
,该parser
用于清理和转换从DOM传递到模型的值。 Validation comes afterwards. 随后进行验证。 If you just want to check if only numbers are written, then you need something like this:
如果只想检查是否只写数字,则需要这样的代码:
ngModel.$validators.validCharacters = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return /[0-9]+/.test(value);
};
I suggest reading the API docs as they explain all ngModelController functionality very thoroughly: click here for thorough docs 我建议阅读API文档,因为它们会非常详尽地解释所有ngModelController功能: 单击此处以获取完整的文档
Second, you are binding to a event everytime your parser is called. 其次,您每次调用解析器时都绑定到一个事件。 The parser is called each time you change the contents of your input element.
每次您更改输入元素的内容时,都会调用该解析器。 If you type the word everytime into your input, you end up binding the event nine times !
如果您每次在输入中键入单词,最终将绑定事件九次 ! Apart from the fact that binding to the event after you changed something is too late as your first event was already fired.
除了在您更改某些内容后绑定到事件这一事实之外,因为您的第一个事件已经被触发,为时已晚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.