Regular Expression
Moderator: General Moderators
-
sathiqali.s
- Forum Newbie
- Posts: 1
- Joined: Fri Dec 08, 2006 4:33 am
Regular Expression
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?
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?
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.. ";
}
?>off the top of my head, and not tested:
you can use just
if you don't want to allow 100 exactly
Code: Select all
preg_match('~(100|\d{1,2}(\.\d{1,2})?)^$~', $your_input)Code: Select all
preg_match('~\d{1,2}(\.\d{1,2})?^$~', $your_input)- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
Even simpler:
Code: Select all
$input = round((float)trim($_GET['whatever']), 2);
if ($input > 100) {
echo 'Bad child';
}- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
You lieno output for me 
Code: Select all
$_GET['whatever'] = -123242353426324.32423423423423;
$input = round((float)trim($_GET['whatever']), 2);
if ($input > 100) {
echo 'Bad child';
}- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK