Reputation: 51
I have a couple of forms with input fields of type number don't seem to have any validation applied by Safari (on Mac OS X Mavericks). That is, if one types letters and hits submits, in every browser a little message appears that you need to put numbers in the field - except Safari. Oh, and Firefox too on this platform.
So, I decided I needed to add validation to my JavaScript code that is handling these form values. I put in a regular expression to reject anything that is not a single-digit number:
if ( !/^([0-9])$/.test(value) ) {
alert ("Please enter a number");
return;
}
In Firefox, this behaves as I hoped. If you enter any letters, or anything other than a single digit, the alert is displayed.
On Safari, if you enter two or more digits, the alert is displayed too, but if you enter non-digit characters, it is not. It acts as if it happily accepts the input, but if I then further add an alert box in an else block below the above to show me what value is, that doesn't get displayed either. There are no errors in the JavaScript console. It's like it just does nothing.
I've stared at the regex a bunch, though it's about as simple as it can be. I'm pretty flummoxed. Any ideas, anyone?
Upvotes: 0
Views: 3305
Reputation: 3456
Misc ways to validate integer ..
// Integers including 0: following values will return true (0, 1, 2 .., 65, etc.)
/^(?:0|[1-9]\d*)$/.test(value);
// Integers, zero not allowed
/^[1-9]\d*$/.test(value);
// Test whether the value is an integer or not (+ sign try to cast the value into a number)
if(Number.isInteger(+value)){/* ... */}
User friendly solution ..
Few months ago, I had to format a user input that had to be either an integer or a float number ; Formatting process is triggered on keypress.
This is what I achieved Fiddle here
Allowed formats
Hope it will help ..
Upvotes: 0
Reputation: 2259
Your regex tests true for a string that is a single digit and false (and enters your negated if condition) otherwise. Must it be only one digit or one or more digits?
Add a + to specify one or more numeric values.
/^([0-9]+)$/
Also do you need or are you using the grouping (parenthesis around the digits)?
/^[0-9]+$/
Upvotes: 0
Reputation: 1579
I don't really like regexes. They are always so error prone and you sometimes don't consider all possible matches. Why don't you use something like this:
if (parseInt("15", 10) !== NaN)
alert("is numeric");
else
alert("please enter a number");
Upvotes: 1