最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Do not allow decimal and text value in textbox on copy and paste - Stack Overflow

programmeradmin3浏览0评论

I dont want to allow to enter and copy and paste decimal value and alphabet in textbox. And I can able to enter negative values. But negative symbol(" - ") should be always in beginning. Please look at the following fiddle fiddle. In this fiddle its not allowing decimal value and alphabet. But if I copy and paste "22.50" like this, it is taking decimal value. How can I Restrict this.

My Requirement,

1) Allow only numbers(positive and negative).

2) " - " symbol should be at beginning. Not allowed in middle or somewhere.

3) Alphabets should not allowed even copy paste also.

4) I can able to copy paste numbers like "2222" and "-2222". But not characters and decimals.

FIDDLE

var input = document.getElementById("myInput");

input.onkeypress = function(e) {    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

    // Allow non-printable keys
    if (!charCode || charCode == 8 /* Backspace */ ) {
        return;
    }

    var typedChar = String.fromCharCode(charCode);

    // Allow numeric characters
    if (/\d/.test(typedChar)) {
        return;
    }

    // Allow the minus sign (-) if the user enters it first
    if (typedChar == "-" && this.value == "") {
        return;
    }

    // In all other cases, suppress the event
    return false;
};
<input type="text" maxlength="10" id="myInput">

I dont want to allow to enter and copy and paste decimal value and alphabet in textbox. And I can able to enter negative values. But negative symbol(" - ") should be always in beginning. Please look at the following fiddle fiddle. In this fiddle its not allowing decimal value and alphabet. But if I copy and paste "22.50" like this, it is taking decimal value. How can I Restrict this.

My Requirement,

1) Allow only numbers(positive and negative).

2) " - " symbol should be at beginning. Not allowed in middle or somewhere.

3) Alphabets should not allowed even copy paste also.

4) I can able to copy paste numbers like "2222" and "-2222". But not characters and decimals.

FIDDLE

var input = document.getElementById("myInput");

input.onkeypress = function(e) {    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

    // Allow non-printable keys
    if (!charCode || charCode == 8 /* Backspace */ ) {
        return;
    }

    var typedChar = String.fromCharCode(charCode);

    // Allow numeric characters
    if (/\d/.test(typedChar)) {
        return;
    }

    // Allow the minus sign (-) if the user enters it first
    if (typedChar == "-" && this.value == "") {
        return;
    }

    // In all other cases, suppress the event
    return false;
};
<input type="text" maxlength="10" id="myInput">

Please help me for doing this.

Share Improve this question asked Mar 8, 2016 at 16:05 sathish kumarsathish kumar 9362 gold badges23 silver badges60 bronze badges 4
  • 1 How about <input type=number>? – Scott Marcus Commented Mar 8, 2016 at 16:14
  • Is your input a part of a form? Can you use pattern validation upon submitting the form? – jritchey Commented Mar 8, 2016 at 16:18
  • Add an alert statement inside of the input.onkeypress function. Then you'll see when this function is filtering inputs. It may not be executed for pasted inputs. – JohnH Commented Mar 8, 2016 at 16:41
  • Tying into the key press is risky, the user can right click and select paste. not sure if the key event will trigger if that happens – QBM5 Commented Mar 8, 2016 at 16:53
Add a ment  | 

6 Answers 6

Reset to default 1

You can use jquery to listen to change in input field as

$('#myInput').bind('input', function(e) {
    //handle the input text here
});

If you want nothing to show when the string contains invalid text, you can set the value of input field to empty as

$("#myInput").val("");

Update :

Here is the demo

$('#myInput').bind('input', function(e) {
var str = $("#myInput").val();
var dec = str.indexOf(".");
var first_char = str.charAt(0);
var isNumber = true;
var haveDecimal = false;

if (first_char == '-' || !isNaN(first_char)) {
    for (i=1; i<str.length; i++) {
        if(isNaN(str.charAt(i)) && str.charAt(i) != '.') {
            isNumber = false;
            break;
        }
    }
}
else {
    isNumber = false;
}

if(dec != -1 && isNumber) {
    str = str.substring(0, str.indexOf("."));
}

if (isNumber) {
    $("#myInput").val(str);
}
else {
    $("#myInput").val("");
}
});

JSFiddle : http://jsfiddle/7XLqQ/99/

My answer is not exactly what you asked, but I'd dare to be blunt and show some unwanted initiative here.

Locking client input to form is impossible. Any input-locking should be server-side.

'Silently eating' input could be irritating for some users, and trying implement it cross-browser is pain in the ass. They are not designed to give that API that would make this job easier and user-friendly (think about mobile devices).

So if easy route is ok for you - you can use HTML5 properties and let modern browsers handle exactly how to take care of input. If you use raw version of the snippet below (i mean copy it to your local machine - FIDDLE is capturing onsubmit events which will skew experience) it wouldn't allow user to send form. It will allow entering wrong symbols but it will indicate mistake.

<!DOCTYPE html>
<html>
  <head>
    <title>123</title>
  </head>
<body>
   <form action="/" method="get">
    <input type="text"
           pattern="-*[0-9]+"
           required="required"
           title="Input number (required)."
    >
    <br>
    <input type="number"
           required="required"
           title="Input number here (required)."
    >
    <br>
    <input type="submit" value="Send">
</form>
</body>
</html>

Cheers. If you are going to make it your way anyways - to take under your control how user is making his input - I'd say you are in for a world of pain. ^_^ Good luck.

You could use the onpaste Event

input.onpaste = function...

For validation I think you are better off using regular expressions

http://www.w3schools./jsref/jsref_obj_regexp.asp

And here is another way to answer your question. You can try this plugin - if it fits your target browsers - then more power to you.

http://digitalbush./projects/masked-input-plugin/

If you're open to using jQuery, you can use jQuery's .change() event handler. The event handler will be called when the value of the input has changed and the input has lost focus. See the code below that I've used in this jsfiddle.

$('#myInput').change(function() {
  var str = $('#myInput').val();
  var pattern = /^(-?)\d+$/;
  var result = pattern.test(str);
  if (result === true) {
    // Do something...
  } else {
    // Do something else...
  }
})

Alternatively, if your input is within a form, you are open to form submission validation (rather than real-time input validation), and you are writing for HTML5-pliant browsers, you can bypass JavaScript and use HTML5's pattern attribute for input validation. See the code below that I've used in this jsfiddle.

<input type="text" maxlength="10" id="myInput" pattern="-?[0-9]+" title="Integers only." required/>

As an alternative, if you are using your input with form submission, and otherwise don't need to access the input value programmatically, you can let the browser handle validation for you (you can even add visual indicators with CSS):

input:invalid {
  color: #ff0000;
  border-color: #ff0000;
}
<form action="#">
  <input type="number" step="1" value="0">
  <input type="submit">
</form>

The step attribute of the above input will not allow any decimals to be present. Any respectable AJAX form submission library or plugin will also take this validation into consideration.


Otherwise, you are looking at a brutal and lengthy grinding of various cross-browser implementation variations and event handlers, in each handler - where the input value is subject to change - checking if the new value matches against a regex such as this:

-?[0-9]+
发布评论

评论列表(0)

  1. 暂无评论