Came across this article while I was searching for a solution of my own. Needed a non-intrusive way to keep people from entering anything by numbers in one field and nothing but letters, numbers or spaces in other fields. I couldn't use pattern="9999" for the numbers as it was not a required field and folks get "yelled at" if they tab through that field. Likewise, could not use pattern="xxx" for the alpha/numeric fields as I also needed to allow spaces.
Leapfrogging from this article and using javascript that previous programmers had developed for that client, I came up with these beautiful handlers, thought I'd share in case someone else needed this elegant solution and ALSO because sometimes I forget and would be able to find this again.
Either in a .js file you include or enclosed in tags:
function numChecker(e)
{
if (!e.value.match(/^[0-9]+$/))
{
e.value = e.value.substring(0.e.value.length -1 );
e.focus();
return false;
}
return true;
}
function charChecker(e)
{
if (!e.value.match(/^[a-zA-Z0-9\ ]+$/))
{
e.value = e.value.substring(0.e.value.length-1);
e.focus();
return false;
}
return true;
}
Then your input or cfinput fields would have OnKeyUp="numChecker(this)"
or OnKeyUp="charChecker(this)"
in their attributes.
As people type, if they enter an invalid character this script will kick in and simply remove that bad character. No extra buttons to click or alerts to dismiss.