Restricting input to textbox: allowing only number

2019-01-02 14:47发布

How can I restrict input to a text-box so that it accepts only numbers and the decimal point?

30条回答
回忆,回不去的记忆
2楼-- · 2019-01-02 15:36

Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.

It's not perfect, but might give some ideas.

app.directive('isNumber', function () {
            return function (scope, elem, attrs) {
                elem.bind('keypress', function (evt) {
                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             

                   //allows numbers, separators and controll keys and rejects others
                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                        //test the string with regex, decline if doesn't fit
                        if (elem[0].value != "" && !regex.test(testValue)) {
                            event.preventDefault();
                            return false;
                        }
                        return true;
                    }
                    event.preventDefault();
                    return false;
                });
            };
        });

Allows:

11 11 .245 (in controller formatted on blur to 1111.245)

11,44

-123.123

-1 014

0123 (formatted on blur to 123)

doesn't allow:

!@#$/*

abc

11.11.1

11,11.1

.42

查看更多
君临天下
3楼-- · 2019-01-02 15:36

I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.

See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.

Here is the working code.

        
        function IsNumeric(e) {
        var IsValidationSuccessful = false;
        console.log(e.target.value);
        document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";
        //console.log("e.Key Value = "+e.key);
        switch (e.key)
         {         
             case "1":
             case "2":
             case "3":
             case "4":
             case "5":
             case "6":
             case "7":
             case "8":
             case "9":
             case "0":
             case "Backspace":             
                 IsValidationSuccessful = true;
                 break;
                 
						 case "Decimal":  //Numpad Decimal in Edge Browser
             case ".":        //Numpad Decimal in Chrome and Firefox                      
             case "Del": 			// Internet Explorer 11 and less Numpad Decimal 
                 if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists
                 {
                     IsValidationSuccessful = false;
                 }
                 else
                 {
                     IsValidationSuccessful = true;
                 }
                 break;

             default:
                 IsValidationSuccessful = false;
         }
         //debugger;
         if(IsValidationSuccessful == false){
         
         document.getElementById("error").style = "display:Block";
         }else{
         document.getElementById("error").style = "display:none";
         }
         
         return IsValidationSuccessful;
        }
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />
    <div id="info"></div>

查看更多
与君花间醉酒
4楼-- · 2019-01-02 15:38

All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1 etc.

I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.

var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>

The oninput event is triggered just after something was changed in the text area and before being rendered.

You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.

查看更多
一个人的天荒地老
5楼-- · 2019-01-02 15:38

Starting from @rebisco answer :

function count_appearance(mainStr, searchFor) {
    return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
    $return = true;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
        $return = false;
    $val = $(evt.originalTarget).val();
    if (charCode == 46) {
        if (count_appearance($val, '.') > 0) {
            $return = false;
        }
        if ($val.length == 0) {
            $return = false;
        }
    }
    return $return;
}

Allows only this format : 123123123[.121213]

Demo here demo

查看更多
还给你的自由
6楼-- · 2019-01-02 15:39

Best and working solution with Pure-Javascript sample Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/

<script>
function removeCommas(nStr) {
    if (nStr == null || nStr == "")
        return ""; 
    return nStr.toString().replace(/,/g, "");
}

function NumbersOnly(myfield, e, dec,neg)
{        
    if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
        return false;
    }
    var allowNegativeNumber = neg || false;
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    var srcEl = e.srcElement ? e.srcElement : e.target;    
    // control keys
    if ((key == null) || (key == 0) || (key == 8) ||
                (key == 9) || (key == 13) || (key == 27))
        return true;

    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;

    // decimal point jump
    else if (dec && (keychar == ".")) {
        //myfield.form.elements[dec].focus();
        return srcEl.value.indexOf(".") == -1;        
    }

    //allow negative numbers
    else if (allowNegativeNumber && (keychar == "-")) {    
        return (srcEl.value.length == 0 || srcEl.value == "0.00")
    }
    else
        return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" /> 

查看更多
无与为乐者.
7楼-- · 2019-01-02 15:39
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
    e= window.event? e.srcElement: e.target;
    while(e.value && parseFloat(e.value)+''!= e.value){
            e.value= e.value.slice(0, -1);
    }
}
查看更多
登录 后发表回答