views:

1469

answers:

3

Hi there,

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

+3  A: 

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.

Julian Aubourg
i already have form submit validation method :D
Dels
+6  A: 

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>
Eibx
Yes, that works for simple character filtering... but what about full-fledged formats like a date ("mm/dd/yy"). You cannot just return false if it's not the proper format or else you won't ever be able to enter the first digits.
Julian Aubourg
No that's true, but it gives a certain idea on how it could be made. Fx. you would only be able to type 0 and 1 in the first charecter of the date string. If the user would type a number above that, the number wouldn't be registered. But yes this specific codes does not do the whole magic.
Eibx
yeah, I just commented for clarity ;)
Julian Aubourg
+3  A: 

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.

Tim Büthe