angularjs - Formatting input type=number fields with commas and also add min max validation
问题描述
I currently have a lot of type=number input fields in a form with min and max validation. The input field will display an error message if user enters more than 6 digits for a 6 digit max number field.
But now I have this requirement to format numbers with commas. I know that you cannot enter comma in type=number input fields. If I make it a text field and add a directive to format the string, now the value becomes a string and I cannot perform min/max validation and also the value is stored as a string and not number.
I need help with figuring out how to format the number with commas and as well as add min/max validation and store it as a number not a string.
解决方案
您可以使用限制字符数量的指令来实现所需的结果。
myApp.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keypress", function(e) {
var char = String.fromCharCode(e.which);
if (e.which != 8 && e.which != 0) {
if (char < '0' || char > '9') {
e.preventDefault();
}
else if (this.value.length == limit) {
e.preventDefault();
}
}
});
}
}
}]);
然后你的输入字段会像这样:
<input type="number" limit-to="6">
这并不完全格式化输入,但它排除了某些字符被字符代码输入。您可以通过在基于字符代码的 if 语句中添加更多条件来允许将逗号添加到输入中。如果您想对此进行格式化,那么我建议您使用 ng-pattern 和正则表达式来获得您想要的确切格式。
最后,我建议使用 angularjs 表单验证。https://docs.angularjs.org/guide/forms 这对于您正在尝试做的事情非常方便。
推荐阅读
- java - 无法获取通知表单扫描程序
- excel - How can I loop through a calendar to open files on VBA?
- java - Is the Java collection method retainAll() guaranteed to leave the order of the list it modifies unaltered?
- firebase - 当我的 Firestore 阅读限制过期时会发生什么?
- google-compute-engine - 到虚拟机的 IAP 隧道
- python - How do I convert "key=value, key=value, ..." to csv when some values contain the delimiter as part of the value?
- statistics - 如何从回归(OLS)系数解释经济意义?
- swift - Require a SwitftUI View in a protocol without boilerplate
- sql-server - BCP 到 SQL Server 的“复制失败”问题(似乎与数据溢出无关)?
- perl - 使用 Perl 变量作为替代表达式