On a project that I was recently working on, I had a series of text input boxes that I wanted to be numeric only fields. I have my PHP form validation to check that the data is numeric before entering any information in to the database, and I always use mysql_real_escape_string() on the data I am saving. But to save loat time and page refreshed, I decided to add some extra validation with the Mootools javascript library which I am using trough out the site already.
Update to Numbers Array
I have updated the Numbers array to include the number pad on full size keyboards.
Allowing Numbers:
Because I have a bunch of inputs that I need validated, I decided that I would assign each input with a matching class, then Scan the page for that class with my Javascript, then only allow specific key codes to be entered.
Your Age...
Inside of my DOM Ready state, I run this simple code.
window.addEvent('domready', function() {
var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
$$('.numeric').each(function(item) {
item.addEvent('keydown', function(key) {
for (i = 0; i < numbers.length; i++) {
if(numbers[i] == key.code) {
return true;
}
}
return false;
});
});
});
If you can see the line I have specified only the Key Codes that are allows, I have allowed for numeric numbers and the Delete Key.
var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
Other Uses:
You could disallow any key entry, This isnt a great idea, but could be used when maybe using an overlay, or special effect.
window.addEvent('domready', function() {
window.addEvent('keydown', function() { return false; });
});
Dissallowing Keys:
You could simply reverse this function, to block a small amount of keys rather than just allowing some, it would be as simple as changing the locations of your return true/false statements.
This example would allow anything except numbers.
window.addEvent('domready', function() {
var numbers = [48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
$$('.numeric').each(function(item) {
item.addEvent('keydown', function(key) {
for (i = 0; i < numbers.length; i++) {
if(numbers[i] == key.code) {
return false;
}
}
return true;
});
});
});