Page 1 of 1

Regular Expression

Posted: Fri Dec 08, 2006 5:40 am
by sathiqali.s
Hi,
I am new to this forum and regular expression. I need to validate a textfield where I need to allow only numeric values and below 100. User may type like 7.5 or 35.50, 34.6, etc. And I need to restrict two digits of decimal values not more than that. eg. 35.56. It should not allow like 34.3456.
Can you anyone help me?

Posted: Fri Dec 08, 2006 5:55 am
by Corvin
Why RegEx? You can do it without any use of RegExs:

Code: Select all

<?php
$textfield = "45.4";

$test = explode(".", $textfield);
// more decimal place than one ?
if ( strlen($test[1]) > 1 ) {
	echo "only 1 decimal place is allowed";
}

// bigger than 100 ?
if ( intval($textfield) > 100 ) {
	echo "must be below 100.. ";
}
?>

Posted: Fri Dec 08, 2006 7:04 am
by sweatje
off the top of my head, and not tested:

Code: Select all

preg_match('~(100|\d{1,2}(\.\d{1,2})?)^$~', $your_input)
you can use just

Code: Select all

preg_match('~\d{1,2}(\.\d{1,2})?^$~', $your_input)
if you don't want to allow 100 exactly

Posted: Fri Dec 08, 2006 8:36 am
by Ollie Saunders
Even simpler:

Code: Select all

$input = round((float)trim($_GET['whatever']), 2);
if ($input > 100) {
   echo 'Bad child';
}

Posted: Fri Dec 08, 2006 8:59 am
by sweatje
Ole:

-123242353426324.32423423423423 passes ;)

Posted: Fri Dec 08, 2006 7:56 pm
by Ollie Saunders
You lie

Code: Select all

$_GET['whatever'] = -123242353426324.32423423423423;
$input = round((float)trim($_GET['whatever']), 2);
if ($input > 100) {
   echo 'Bad child';
}
no output for me :)

Posted: Fri Dec 08, 2006 8:33 pm
by sweatje
Ole, I was making a point that a large negative number passes your validation, where as I assumed the original poster would not care for it.

Posted: Sat Dec 09, 2006 6:21 am
by Ollie Saunders
Oh ok... very good, carry on.