Forum Moderators: open

Message Too Old, No Replies

Dont want decimal in number

         

YuviG

5:17 am on May 29, 2007 (gmt 0)

10+ Year Member



Hi Friends

I have a problem with javascript like i have a textfield and i want when user enters numeric value with decimals (23.4) it should show an alert "Plz enter valid number!" ...
i.e., Only numbers 234 is allowd but not 23.4

any help.?

thanks

Fotiman

2:40 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You could compare the value entered against a regular expression that only matches digits.


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.

Dabrowski

5:19 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Should that '+' be there?

I'd have done /^[0-9]+$/

Fotiman

5:56 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



/^[0-9]+$/ does not work.

/[^0-9+]/g is doing a gobal match. It's looking for any 1 or more characters that is not in the set 0-9.

Dabrowski

6:16 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



/^[0-9]+$/ does not work

Have you tested that? Are you sure? ;)

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.

Fotiman

7:30 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month





/^[0-9]+$/ does not work

Have you tested that? Are you sure? ;)

Yes, I have tested that, so yes, I'm sure. :) But read on for clarification...


<!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.

Dabrowski

9:17 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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.

mehh

9:41 am on May 30, 2007 (gmt 0)

10+ Year Member



Why are you doing RegEx when parseInt() does the job for us?

Dabrowski

10:29 am on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



LOL! As you will see from Fotiman and I, we like the hard way!

Dabrowski

12:11 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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____Invalid

You see, parseInt will still report ok for a decimal point, which we want to rule out.

zangs

12:20 pm on May 30, 2007 (gmt 0)

10+ Year Member



Hello
You can do this by lots of way..
I have 2 js function for this..

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;
}

Arno_Adams

1:08 pm on May 30, 2007 (gmt 0)

10+ Year Member



Here's something I just put together:

function checkVal(str) {
for(var i=0; i<str.length; i++) {
if(isNaN(str.charAt(i))) {
return false;
}
}
return true;
}

HTH, AA

Dabrowski

2:46 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



zangs, those 2 ways would work, but much more complicated than the regex.
Arno_Adams, isNan would still accept the decimal point, which in this case we don't want.

A RegExp is by far the best way here. Please see Fotiman's more recent post.

mehh

3:51 pm on May 30, 2007 (gmt 0)

10+ Year Member




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____Invalid

You see, parseInt will still report ok for a decimal point, which we want to rule out.


What i ment was something like:

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

Dabrowski

4:44 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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]

Fotiman

7:27 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




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.

Dabrowski

9:06 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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.

Fotiman

9:11 pm on May 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



LOL

Arno_Adams

8:23 am on May 31, 2007 (gmt 0)

10+ Year Member



@Dabrowski:
The function I wrote works OK. It returns false if there's a decimal point.
It checks if each character is a number or not.

AA

Dabrowski

10:24 am on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry Arno I missed that, yes it would work.

YuviG have you been following this? Did you get your input box working right?

Bernard Marx

1:49 pm on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



(Just to add to the trivia!)

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.

Fotiman

4:02 pm on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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 . :)

vincevincevince

4:05 pm on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For ultimate speed, listen for the decimal point keystroke and then you can have the error ready before the guy finishes typing the number...

Fotiman

4:18 pm on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The event handlers discussed already can be applied to whatever event you want: keypress, form submit, etc.

mehh

6:30 pm on May 31, 2007 (gmt 0)

10+ Year Member




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?

Fotiman

8:39 pm on May 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




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?

Here are the results I saw using 200,000 loops.
Firefox 1.5.0.11 on Win XP
parseInt method averaged 0.006977 ms / loop
regExp method averaged 0.022001 ms / loop

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.

Dabrowski

12:47 am on Jun 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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]

Fotiman

3:17 pm on Jun 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




<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">

Yeah, like that. onclick instead of onClick. :-)


Using getTime as a benchmark, as I guess you've been doing Fotiman,

Yup.

it takes 0ms to perform the test function!

All of the methods discussed so far (parseInt, regexp.test, string.match) will appear to take 0ms on a single call. There is actually some very small amount of time which can only be measured by repeating the call a bunch of times (hence, the 200,000 loop previously mentioned). But basically, you won't be able to differentiate the times on any of these for a single call.

Dabrowski

3:28 pm on Jun 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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]

Fotiman

3:49 pm on Jun 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



LOL! :-)
This 33 message thread spans 2 pages: 33