restrict user input using javascript

2019-04-28 22:51发布

问题:

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

回答1:

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>


回答2:

This question has already an accepted answer, but I think there is a better solution to this. You don't have to implement that yourself on keydown etc., there are libraries for that. They call the technique you describe "input masks". Check out this jQuery plugin it does exactly what you want.



回答3:

You can use specific libs like jQuery Validate (or whatever your JS framework offers) on form submit. The other solution is to control the value on the keyUp & blur events but it can become quite messy to decide what to do with ill-formated entry (especially when the format is a bit complex -- ie not just undesired characters). So, all in all, I'd recommend client-side control on submit.