Regular Expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
sathiqali.s
Forum Newbie
Posts: 1
Joined: Fri Dec 08, 2006 4:33 am

Regular Expression

Post 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?
Corvin
Forum Commoner
Posts: 49
Joined: Sun Dec 03, 2006 1:04 pm

Post 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.. ";
}
?>
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post 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
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Even simpler:

Code: Select all

$input = round((float)trim($_GET['whatever']), 2);
if ($input > 100) {
   echo 'Bad child';
}
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post by sweatje »

Ole:

-123242353426324.32423423423423 passes ;)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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 :)
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Oh ok... very good, carry on.
Post Reply