Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 233
  • Last Modified:

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:


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>";

  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

1 Solution
if ($matched == 0)//TWO equal signs needed
willow87Author Commented:
Ah!  I was so close.  Showing what a beginner I am by missing that one. Works perfectly now - many thanks!

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now