Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restrict user input using javascript

Can someone show me some example for restricting user input (on input tag) in Javascript?

Something that when we set the input (type="text") to only accept numeric, so it will ignore any other input except for numeric...

I think it's handy for number input (such as zip, credit card, money, value, score, date etc...), and if you can please show me how to create input with pattern, something like:

Please Input Date:
|-----------------|
|     /     /     |
|-----------------|

PS: I heard WebForms 2.0 will support this in the future... (Acid 3 compliant browser?)

input type="date"
input type="time"
input type="number"
input type="money"

But it was only news from future :D

like image 446
Dels Avatar asked Mar 18 '09 09:03

Dels


1 Answers

This might help you.

http://www.w3schools.com/jsref/event_onkeydown.asp

<html>
<body>

<script type="text/javascript">
function noNumbers(e)
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
return !numcheck.test(keychar);
}
</script>

<form>
<input type="text" onkeydown="return noNumbers(event)" />
</form>

</body>
</html>
like image 166
はると Avatar answered Nov 15 '22 06:11

はると