How to check a number is valid when a form is submitted to your PHP code?

You have a form on your website and you are collecting numbers

You want to make sure they are valid numbers.

How do you make sure they are valid numbers?

First, you can validate them client-side in the browser, before the form is submitted to your server

With HTML5 you can define the input field type as email and make it a required field, like this:

<input type="number" name="email" required>

Example of how the number input looks

The number input also supports a range of acceptable numbers, so if you only wanted to numbers between 1 and 10, you would set the min and max attribtues like this:

Example of how the number input with a range looks

<input type="number" min="1" max="10" name="number" required>

Note that most of the frequently used browsers will support the above functionality.

Validating the input client side is one thing, but you have to validate it on the server also.

You can use this PHP code, to make sure that submitted number is really valid:


// Grab the POSTed number input field
$number = $_POST['number'];
$number_range = $_POST['number_range'];

// Use filter_var to check if the number is valid
if (filter_var($number, FILTER_VALIDATE_INT) === false) {
echo("$number is not a valid number");
} else {
echo("$number is a valid number");
}

// Use filter_var to check if the number is valid and within the range
if (filter_var($number_range, FILTER_VALIDATE_INT, 1, 10) === false) {
echo("$number_range is not a valid number");
} else {
echo("$number_range is a valid number");
}

For a bare bones code sample, demonstrating the above you can find it below:

If you found this post helpful, please subscribe below for more.

Leave a Reply