...

View Full Version : validate that field can ONLY contains numbers and a decimal point



ventura
01-14-2003, 07:37 PM
how do i validate a text field so that it can only contain numbers (0-9) and an optional decimal point?

arnyinc
01-14-2003, 08:37 PM
I got this mostly from irt.org. It just checks to see if math can be done on the input, which should be any valid number that a user could enter.



<html>
<script language="javascript">
function check(contents) {
if (((contents / contents) != 1) && (contents != 0))
alert('This box requires a number')
else
alert('This is a number')
}
</script>


<body>
<form name="myform">
<input type="text" name="textbox1">
<input type="button" onclick="check(document.myform.textbox1.value)" value="verify">
</form>
</body>
</html>

beetle
01-14-2003, 09:04 PM
function isDecimal( str )
{
return /^\d*\.?\d*$/.test( str );
}

whammy
01-15-2003, 01:20 AM
What beetle said. Although if I'm not mistaken that would also return true for an empty or null string? ;)

An easy fix?:

<script type="text/javascript">
<!--
function isDecimal( str )
{
return str != "" ? /^\d*\.?\d*$/.test( str ) : false;
}
// -->
</script>

beetle
01-15-2003, 02:08 AM
You could do it that way, or build it into the regex

function isDecimal( str )
{
return /^(?:\d+)|(?:\d*\.?\d*)$/.test( str );
}

C'mon Whammy, aren't you always lording over regexs? :p

whammy
01-16-2003, 12:03 AM
Yeah... but I was just fixing it quick... BTW the regex above doesn't work, it seems to accept everything, even "asdf". And I'm not sure about the non-matching(?) i.e. (?:whatever) groups, if you're only testing against the regex - isn't that unnecessary if you aren't going to be replacing per group, i.e. '$1 $2', and you don't want the group to be "assigned" to $1 or whatever?

As you can see, I forgot the technical terms, lol. ;)

I fixed it regex only like this:



<script type="text/javascript">
<!--
function isDecimal(str) {
return /^\d+(\.\d+)?$|^\.\d+$/.test(str);
}
// -->
</script>


I'm sure beetle can shorten it though, and I am now eagerly awaiting his response. ;)

... is there an "and/or" operand for regex's?

Just because my signature says 'learn em, doesn't mean I've TOTALLY mastered them yet! But I can definitely write regex's that get the job done, I just make sure I test the (*&^ out of them. ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum