Reputation: 936
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.
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.
Upvotes: 5
Views: 3621
Reputation: 3356
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.net/7XLqQ/99/
Upvotes: 1
Reputation: 31932
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]+
Upvotes: 0
Reputation: 136
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-compliant 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/>
Upvotes: 0
Reputation: 852
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.com/projects/masked-input-plugin/
Upvotes: 0
Reputation: 852
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.
Upvotes: 1
Reputation: 364
You could use the onpaste Event
input.onpaste = function...
For validation I think you are better off using regular expressions
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Upvotes: 0