Forum Moderators: open
var reg = /[^0-9+]/g;
var el = document.getElementById('exampleInput');
var val = el.value;
if (val.match(reg)) {
// Invalid characters found
alert('Please enter a valid number.');
}
Just work this in to your form submit event handler.
/^[0-9]+$/ does not work
Have you tested that? Are you sure? ;)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<script type="text/javascript">
function test() {
// This reg works:
// var reg = /[^0-9+]/g;
// This reg does not:
var reg = /^[0-9]+$/;
var el = document.getElementById('exampleInput');
var val = el.value;
if (val.match(reg)) {
// Invalid characters found
alert('Please enter a valid number.');
}
else {
alert('all is well');
}
}
</script>
</head>
<body>
<input id="exampleInput">
<input type="button" onclick="test();" value="test">
</body>
</html>
It's looking for the beginning, then some numbers, then the end. Anything else will throw an error. Kinda the opposite method to yours. I didn't realise you could put a '+' inside []'s.
I see what yours is supposed to do, and that is why it wasn't working for me... you said it best "Kinda the opposite method to yours". Yours should work if you swap the conditions in the if/else example I posted above. :)
My example does this:
/[^0-9+]/g;
[^...] matches any character not between the brackets. Therefore:
/[^0-9]/g;
Will search globally for any character that is not 0-9. I don't think the + is actually needed in my original example.
should work if you swap the conditions in the if/else example
Fair enough. Yes you were right, a '+' is pointless with the /g. But to be honest, as we only need 1 charater to trigger this you could make do with neither.
I was questioning whether the '+' should be inside the []'s. i.e. [0-9+] will match 0 thru 9 and the + sign, [0-9]+ will match 0 thru 9 at least once? I'm not entirely sure.
Take these examples......
Text_____Should be___parseInt___RegExp
123______Valid_______Valid______Valid
12.3_____Invalid_____Valid______Invalid
12oops___Invalid_____Invalid____Invalid
You see, parseInt will still report ok for a decimal point, which we want to rule out.
function onlynumber(value,length){
chk1="1234567890";
for(i=0;i<length;i++)
{
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function checkValidDigit()
{
val = event.keyCode;
if(val<48 && val!=46)
{
event.keyCode=0;
}
if(val>57)
{
event.keyCode=0;
alert("Please Enter Numeric Value");
}
return true;
}
Actually parseInt won't work, the point was that only numbers should be considered valid.Take these examples......
Text_____Should be___parseInt___RegExp
123______Valid_______Valid______Valid
12.3_____Invalid_____Valid______Invalid
12oops___Invalid_____Invalid____InvalidYou see, parseInt will still report ok for a decimal point, which we want to rule out.
function checkInt(inp){
var p=parseInt(inp);
if(p==inp)
return true;
return false;
}
function checkInt(inp){
var p=parseInt(inp);
if(p==inp)
return true;
return false;
}
I see, that would work.
function checkInt(inp){
return inp.match( /[^0-9]/);
}
Which is shorter? ;)
Foti, I've used neither a + or /g, we only need a single match for it to fail in this case.
Actually mehh, yours would work just the same as:
function checkInt(inp){
return ( inp = parseInt( inp));
}
As for faster, more memory? It's one line. If you can accurately measure a difference then please let me know.
[edited by: Dabrowski at 4:45 pm (utc) on May 30, 2007]
function checkInt(inp){
var p=parseInt(inp);
if(p==inp)
return true;
return false;
}wouldn't that be faster and less memmory intensive? optimization is always important
Yes, that is very slightly faster, but the difference is negligable. You will only notice the difference if you are comparing a massive number of values. For the simple case of validating a single field, they are for all intents and purpose, equal. Comparing 10,000 values, the parseInt method is about 80ms faster. Can you tell the difference between 94ms and 172ms? I know I can't.
Each method has pro's and cons.
Comparing 10,000 values, the parseInt method is about 80ms faster. Can you tell the difference between 94ms and 172ms? I know I can't.
That's for 10,000? Whoa! That's fast. That means that for a single one, the parseInt method is 8ns, (that's nanoseconds) faster. That sure is a performance gain worth pursuing.
Comparing 10,000 values, the parseInt method is about 80ms faster.
I reckon that's because
parseInt is being compared to the match method. The method returns an array or null. Really, the test method of the RegExp should be used instead (returns a simple boolean). /^[0-9]$/.test(inp); I dare say it would actually be faster.
Ah, excellent point Bernard Marx. In fact, changing my test case to use the test method instead of match actually does result in both the parseInt method and the test method taking nearly identical time for 10,000 tests . happy! :)
I also tested it. I did 200,000 loops in Firefox 2.0.0.4 on windows XP and got a difference of 13.5 micro seconds per loop in favor of parseInt on average. does this match your results?
parseInt is faster, but again, only noticable across huge iterations.
Internet Explorer 6 on Win XP
parseInt method averaged 0.012454 ms / loop
regExp method averaged 0.013025 ms / loop
The difference between the two methods on IE is essentially un-noticable even at 200,000 records.
For ultimate speed, listen for the decimal point keystroke and then you can have the error ready before the guy finishes typing the number
Couldn't resist! LOL!
<input type='text' onKeyUp='checkDot();'>
<input type="button" onclick="test();" value="test">var aDot;
function checkDot( evt) {
var e = evt ¦¦ event;
var elm = e.target ¦¦ e.srcElement;aDot = ( /\./.test( elm.value));
}function test() {
if( aDot) alert( "No dots please!");
}
Using getTime as a benchmark, as I guess you've been doing Fotiman, it takes 0ms to perform the test function!
[edited by: Dabrowski at 12:50 am (utc) on June 1, 2007]
<input type='text' onKeyUp='checkDot();'>
If you're going to use obtrusive JavaScript (ie - the event handlers as attributes in the HTML), at least avoid the camelCase attributes (onkeyup instead of onKeyUp). ;-)
<input type="button" onclick="test();" value="test">
Using getTime as a benchmark, as I guess you've been doing Fotiman,
it takes 0ms to perform the test function!
If you're going to use obtrusive JavaScript (ie - the event handlers as attributes in the HTML), at least avoid the camelCase attributes (onkeyup instead of onKeyUp). ;-)
Only doing that so I don't have to bother with the whole addEvent malarkey.
What's wrong with camelCase? Makes it more readable. It's not xhtml you know.
All of the methods discussed so far (parseInt, regexp.test, string.match) will appear to take 0ms on a single call
Ahh yes, but as the answer is pre-calculated with an onBlur, the nanoseconds are moved away from the time you hit the submit. Thus making the submit 8ns faster.
This is all getting kinda silly now! :D I hope YuviG tells us he's fixed it so we can all move on!
[edited by: Dabrowski at 3:29 pm (utc) on June 1, 2007]