如何只允许在输入中输入数字(数字和小数点)? [英] How to allow only a number (digits and decimal point) to be typed in an input?

查看:26
本文介绍了如何只允许在输入中输入数字(数字和小数点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angularjs 的新手.我想知道只允许在文本框中输入有效数字的方法是什么.例如,用户可以输入1.25",但不能输入1.a"或1..".当用户尝试输入下一个会使其成为无效数字的字符时,他无法输入.

提前致谢.

解决方案

您可以尝试使用此指令来阻止将任何无效字符输入到输入字段中.(更新:这依赖于对模型有明确了解的指令,这对于可重用性来说并不理想,请参阅下面的可重用示例)

app.directive('isNumber', function () {返回 {要求:'ngModel',链接:功能(范围){scope.$watch('wks.number', function(newValue,oldValue) {var arr = String(newValue).split("");如果(arr.length === 0)返回;if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) 返回;if (arr.length === 2 && newValue === '-.') 返回;如果(isNaN(新值)){scope.wks.number = oldValue;}});}};});

它还说明了这些情况:

  1. 从一个非空的有效字符串到一个空字符串
  2. 负值
  3. 负十进制值

我在这里创建了一个 jsFiddle 以便您可以看到它是如何工作的.

更新

根据 Adam Thomas 关于不直接在指令中包含模型引用的反馈(我也认为这是最好的方法),我更新了我的 jsFiddle 提供一种不依赖于此的方法.

该指令利用本地作用域到父作用域的双向绑定.对指令内变量所做的更改将反映在父作用域中,反之亦然.

HTML:

<div ng-controller="Ctrl"><number-only-input input-value="wks.number" input-name="wks.name"/>

</表单>

角度代码:

var app = angular.module('myapp', []);app.controller('Ctrl', function($scope) {$scope.wks = {number: 1, name: 'testing'};});app.directive('numberOnlyInput', function () {返回 {限制:'EA',模板:'<input name="{{inputName}}" ng-model="inputValue"/>',范围: {输入值:'=',输入名称:'='},链接:功能(范围){scope.$watch('inputValue', function(newValue,oldValue) {var arr = String(newValue).split("");如果(arr.length === 0)返回;if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) 返回;if (arr.length === 2 && newValue === '-.') 返回;如果(isNaN(新值)){scope.inputValue = oldValue;}});}};});

I am new to angularjs. I am wondering what is the way to allow only a valid number typed into a textbox. For example, user can type in "1.25", but cannot type in "1.a" or "1..". When user try to type in the next character which will make it an invalid number, he cannot type it in.

Thanks in advance.

解决方案

You could try this directive to stop any invalid characters from being entered into an input field. (Update: this relies on the directive having explicit knowledge of the model, which is not ideal for reusability, see below for a re-usable example)

app.directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope) {    
            scope.$watch('wks.number', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.wks.number = oldValue;
                }
            });
        }
    };
});

It also accounts for these scenarios:

  1. Going from a non-empty valid string to an empty string
  2. Negative values
  3. Negative decimal values

I have created a jsFiddle here so you can see how it works.

UPDATE

Following Adam Thomas' feedback regarding not including model references directly inside a directive (which I also believe is the best approach) I have updated my jsFiddle to provide a method which does not rely on this.

The directive makes use of bi-directional binding of local scope to parent scope. The changes made to variables inside the directive will be reflected in the parent scope, and vice versa.

HTML:

<form ng-app="myapp" name="myform" novalidate> 
    <div ng-controller="Ctrl">
        <number-only-input input-value="wks.number" input-name="wks.name"/>
    </div>
</form>

Angular code:

var app = angular.module('myapp', []);

app.controller('Ctrl', function($scope) {
    $scope.wks =  {number: 1, name: 'testing'};
});
app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input name="{{inputName}}" ng-model="inputValue" />',
        scope: {
            inputValue: '=',
            inputName: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                }
            });
        }
    };
});

这篇关于如何只允许在输入中输入数字(数字和小数点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆