How to Perform Number Validation in PHP 


               


How to Perform Number Validation in PHP

php


In this article, we will go over how to perform number, or numeric, validation of a form field filled in by a user, to make sure that the data entered is, in fact, a numeric value.

This may be necessary for a slew of forms filled out on the web. Examples of these are credit card numbers, zip codes, house numbers, telephone numbers, cash amounts, etc. These are all form fields where we want only numbers entered in to the form field. If any characters in the sequence are non-numeric, then we want to tell the user that the sequence of characters which they entered in are not valid. This is what is referred to as number validation.

Below is an example of a form field which checks for number validation. Only numbers can be entered in to the form field, only numeric values. If non-numeric values are entered, then the form field catches this and tells the user that s/he has made an error.





Result



Above is a form which checks for number validation. In this form, it is wanted that users enter numbers only into the form field. If a user enters a nonnumeric character, an error is thrown and the user is told to enter numbers only into the field.


PHP

So how do we perform number validation in PHP on a form field to make sure only numbers have been entered?

The answer is, we use a function in PHP called the is_numeric function.

The is_numeric function is used to check whether the character(s) which are entered. If all the characters are numeric, it returns a true value. If all the characters are not numeric, it returns a false, or not true, value.

Knowing now how this function works, we can implement it based on an if-else statement. If true, we can make it execute one statement. If false, we can make it execute another statement, such as the form above does.

HTML Code

This HTML code creates the text field in which a user enters characters.

The important thing we need to know from this HTML Code is the "name" attribute of the text field, which in this case is number. We will need to know this for the PHP code, because the "name" attribute is what we use in PHP of the HTML form field to test the characters that the user enters into this field.

PHP Code



The is_numeric() function checks to see if the characters entered into a field are numbers or not. If all the characters are numbers, it returns true. If all the characters are not numeric, it returns false.

Here we simply do an if-else statement. If all the characters are numbers, it tells the user which number was entered and that it is valid. If all the characters are not numbers, it tells the user he has made an error and that all characters must be numbers.

The variable $form_result is there for determining if the submit button has been clicked. If it has, it performs the next step.


HTML Comment Box is loading comments...