Link to home
Start Free TrialLog in
Avatar of willow87
willow87

asked on

regex in PHP to enter user weight

I have a from where users enter their weight.  The form is posted to a page (code below) which validates the entered weight and updates the database.

It is the validation (using preg_match) that I am having trouble with.  Examples of acceptable format:

178
178.0
97
97.6

In english, a number between 10 and 999, with or without one decimal point.

If the format is acceptable, the page should process the form (ie. update the database).  With the current code, the form is processed no matter what is entered.  I have tried simplifying the regex, eg. (preg_match("/^\d)$/", $weight)); but the form will be processed if I enter a letter or number.


// database connection and other facebook code above
// Greet the currently logged-in user!
echo "<p>Hello, <fb:name uid=\"$user_id\" useyou=\"false\" />!</p>";

if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  die('No post.');
}
$weight = (string) $_POST['weight'];
if (empty($weight))
{
  die('You did not enter anything. Please go back.');
}

$matched = (preg_match("/^[1-9]\d{1,2}((\.\d){0,1})$/", $weight));

if ($matched = 0)

{
  die('Your weight does not follow the
required format (explain correct format...). Please try again.');
}

echo sprintf('Thank you!', $user);


//  This php script catches a posted form and writes the result and userid of whoever posted it
      if($_POST['add'] == "true")
      {
          $weight = $_POST['weight'];
$date=date("Y-m-d") ;       
mysql_query("INSERT INTO weight (bookfaceuserid, weight, date) VALUES('$user', '$weight', '$date')");
         
         
      }

?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of willow87
willow87

ASKER

Ah!  I was so close.  Showing what a beginner I am by missing that one. Works perfectly now - many thanks!