Skip to content

Instantly share code, notes, and snippets.

@swape
Created May 21, 2013 10:38
Show Gist options
  • Save swape/5618896 to your computer and use it in GitHub Desktop.
Save swape/5618896 to your computer and use it in GitHub Desktop.
Limiting an input field to only accept numbers
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
//<input type="number" name="mynumber" value="" placeholder="number" onkeypress="validate(event)" id="number-0" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment