I first tried solving this using jQuery, but I wasn't happy about unwanted characters (non-digits) actually appearing in the input field just before being removed on keyup.
Looking for other solutions I found this:
Integers (non-negative)
<script>
function numbersOnly(oToCheckField, oKeyEvent) {
return oKeyEvent.charCode === 0 ||
/\d/.test(String.fromCharCode(oKeyEvent.charCode));
}
</script>
<form name="myForm">
<p>Enter numbers only: <input type="text" name="myInput"
onkeypress="return numbersOnly(this, event);"
onpaste="return false;" /></p>
</form>
Source: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onkeypress#Example
Live example: http://jsfiddle.net/u8sZq/
Decimal points (non-negative)
To allow a single decimal point you could do something like this:
<script>
function numbersOnly(oToCheckField, oKeyEvent) {
var s = String.fromCharCode(oKeyEvent.charCode);
var containsDecimalPoint = /\./.test(oToCheckField.value);
return oKeyEvent.charCode === 0 || /\d/.test(s) ||
/\./.test(s) && !containsDecimalPoint;
}
</script>
Source: Just wrote this. Seems to be working.
Live example: http://jsfiddle.net/tjBsF/
Other customizations
- To allow more symbols to be typed just add those to the regular expression that is acting as the basic char code filter.
- To implement simple contextual restrictions, look at the current content (state) of the input field (oToCheckField.value)
Some things you could be interested in doing:
- Only one decimal point allowed
- Allow minus sign only if positioned at the start of the string. This would allow for negative numbers.
Shortcomings
- The caret position is not available inside the function. This greatly reduced the contextual restrictions you can implement (e.g. no two equal consecutive symbols). Not sure what the best way to access it is.
I know the title asks for jQuery solutions, but hopefully someone will find this useful anyway.