PHP Form Validation: Numeric elements

This entry is part 3 of 7 in the series PHP Form Validation

To ensure that a submitted value is an integer or floating-point numeric number, use the conversion functions intval() and floatval().

They give you the number (integer or floating point) inside a string, discarding any extraneous text or alternative number formats.

You can use the following code to check for integer:

if ($_POST['age'] != strval(intval($_POST['age']))) {
    $errors[] = 'Please enter a valid age.';

And to check for floating-point number:

if ($_POST['price'] != strval(floatval($_POST['price']))) {
    $errors[] = 'Please enter a valid price.';


Series Navigation<< PHP Form Validation: Required elements
PHP Form Validation: Removing whitespace >>