How Can We Get A Javascript Program To Prevent Numeric Input?
Solution 1:
If you want to exclude numbers just prevent them from being entered by replacing them with regEx. You can tell the user that they're not allowed to enter numbers as well..
//collect the stringvar userStr = getTheString();//whatever the source of the string is... probably called onKeyUpif(userStr.match(/\d/)){
userStr = userStr.replace(/\d+/g,"");//[edited to include all digits]alert("no numbers please");
}
[edit] This sounds like a homework assignment, so to be clear, regular expressions are a really powerful way to do all sorts of string manipulation and validation. In the above example I am testing (using match) to see if any digits exist in the string. I recommend running this whenever the user lifts their finger from the keyboard, that way you are guaranteed to prevent unauthorized input. The replace() method seeks out any and all digits (\d+) in the string and replaces them with the second parameter, which is just an empty string. You can obviously do this all in much more convoluted ways, with loops and your own string methods, going through the string letter by letter and then extracting the number chars, and if your teacher wishes to see you figure this out without the comforts of regEx (which is totally reasonable, for a beginner programmer who has to learn algorithmic thinking) then you should say that, and we'll gladly help you do it the "ugly" way.
Cheers.
Solution 2:
You could use this javascript function.
function onlyNumbers(event) {
var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (Key == 13 || (Key >= 48 && Key <= 57)) returntrue;
elsereturnfalse;
}
usage:
<inputtype="text" onkeypress="return onlyNumbers(event);" />
This will prevent any numeric input. If you just want to alert the user, you could use this one.
function onlyNumbers(event) {
var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (Key == 13 || (Key >= 48 && Key <= 57)) returntrue;
else alert("Error");
}
Hope this answers your question.
Solution 3:
See this jsfiddle for a way to check input. Basisically it periodically scans the input fields, reads it's input and formatting rules and warns if the field value doesn't comply to these rules. This approach also catches values that are pasted (Ctrl-V) into the input field.
Post a Comment for "How Can We Get A Javascript Program To Prevent Numeric Input?"