当用户输入字符时,我遇到了输入类型数字验证
问题。
当用户退出时它就消失了。
经过一番研究,我找到了几个解决方案,最好的一个是 link
这里给出的解决方案是使用以下指令
app.directive('toNumber', function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
ctrl.$parsers.push(function (value) {
return parseFloat(value || '');
});
}
};
});
如果用户尝试输入除数字之外的第一个字符,此解决方案可以正常工作。但是,当用户输入比方说 1W
时,它不起作用。它允许输入此模式。
可能,我需要修改此指令以阻止输入 1W、1.W、1WWW(有效数字后的任何字符)
模式。
有什么帮助吗?
另外,
如果有更好的解决方案来满足我正在寻找的问题,请分享。 我的问题是:在 IE 上,当用户在输入类型数字中输入字符并跳出时,数字就会消失,并且我无法使用 Angular $error 显示错误。
最佳答案
尝试这个指令
userapp.directive('priceValidator', [function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
}])
关于javascript - Angular 验证输入类型=“number”验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586789/