AngularJS输入[type =“number”]验证仅允许输入数字

时间:2015-08-11 19:46:35

标签: angularjs validation meteor

我有一个输入框询问一个数字,我想要做的是确保用户不输入任何字母或任何无效的数字。

到目前为止,这是我的代码:

    <form name="userForm" novalidate>
        Calories Needed : 
        <input type="number" min="0" ng-model="user.calories">
    </form>

我一直在寻找使用AngularJS的方法,但没有运气。我遇到了他们建议创建指令的帖子,但我正在寻找另一种技术。我还是初学者,所以我不想只使用代码来了解究竟发生了什么。

2 个答案:

答案 0 :(得分:2)

你很幸运我有一个指令我在这个例子中到处使用。

就像在输入上拍打 <input valid-number /> 一样简单。瞧!

angular.module('yourApp')
 .directive('validNumber', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            // make sure we're connected to a model
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                // this is a test for whether it's undefined (from textbox)
                // or null when using type="number"
                if (val === undefined || val === null) {
                    val = '';
                }

                // here we try and clean it to make sure it's only numbers
                var clean = val.toString().replace(/[^0-9]+/g, '');

                // if a letter/etc got in there, set the model to the "cleaned" number value
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

            // this is to test for "32" = SPACEBAR
            // and "101" = e (Chrome for some reason let's E go through in type="number"
            element.bind('keypress', function (e) {
                var code = e.keyCode || e.which;

                // Remove code === 101 part if you want 'e' to go through
                if (code === 101 || code === 32) {
                    e.preventDefault();
                }
            });
        }
    };
});

答案 1 :(得分:0)

您需要阅读Angular的表单验证 - tutorial

就像在输入中添加“required”和表单元素的“novalidate”一样简单:

<form name="testForm" novalidate>
       <input type="number" required name="numberinput" class="form-control" ng-model="someNumber">
</form>

plunker