首页 > 解决方案 > 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.

标签: angularjshtml

解决方案


您可以使用限制字符数量的指令来实现所需的结果。

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 这对于您正在尝试做的事情非常方便。


推荐阅读