Php validation no numbers

How to Perform Number Validation in 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.

Читайте также:  Python закончить работу программы

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.

Источник

Validating a Phone Number in PHP

In this short tutorial, we’re going to look at validating a phone number in PHP. Phone numbers come in many formats depending on the locale of the user. To cater for international users, we’ll have to validate against many different formats.

In this article

Validating for Digits Only

Let’s start with a basic PHP function to validate whether our input telephone number is digits only. We can then use our isDigits function to further refine our phone number validation.

We use the PHP preg_match function to validate the given telephone number using the regular expression:

This regular expression checks that the string $s parameter only contains digits 1 and has a minimum length $minDigits and a maximum length $maxDigits . You can find detailed information about the preg_match function in the PHP manual.

Checking for Special Characters

Next, we can check for special characters to cater for telephone numbers containing periods, spaces, hyphens and brackets .-() . This will cater for telephone numbers like:

The function isValidTelephoneNumber removes the special characters .-() then checks if we are left with digits only that has a minimum and maximum count of digits.

International Format

Our final validation is to cater for phone numbers in international format. We’ll update our isValidTelephoneNumber function to look for the + symbol. Our updated function will cater for numbers like:

tests whether the given telephone number starts with + and is followed by any digit 9 . If it passes that condition, we remove the + symbol and continue with the function as before.

Our final step is to normalize our telephone numbers so we can save all of them in the same format.

Key Takeaways

  • Our code validates telephone numbers is various formats: numbers with spaces, hyphens and dots. We also considered numbers in international format.
  • The validation code is lenient i.e: numbers with extra punctuation like 012.345-6789 will pass validation.
  • Our normalize function removes extra punctuation but wont add a + symbol to our number if it doesn’t have it.
  • You could update the validation function to be strict and update the normalize function to add the + symbol if desired.

This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.

Источник

How To Validate Phone Numbers Using PHP

Phone Number Validation in PHP

PHP is a very popular server-side programming language. One of the obvious task for a server-side programming language is to process forms. Forms are used to get data from website users. You could receive different inputs from what you expected due to mistakes of users. Also, hackers could use forms to access to your internal data. Hence, it is very important to validate user input data before using them for various purposes.

Читайте также:  Elements in html meaning

Phone numbers are an essential input field in many forms. There are two ways that you can use to validate the phone numbers in PHP. you can either use PHP inbuilt filters or regular expressions for that purpose.

Phone numbers are different from country to country. When you are creating a web application that will be used by people around the globe, you have to write codes which verify each of these requirements.

You might like this :

Phone Number Validation in PHP

Using inbuilt PHP filters easier. But, as there are different types of formats for phone numbers, you have to use regular expressions to validate these phone numbers. PHP provides you with several very powerful functions for parsing regular expressions.

Anyway, we will discuss both methods in this tutorial. First, we will study PHP filters.

Validating Phone Numbers with Filters

We don’t know what will user enter in the input fields. There are some certain characters that we can expect in a phone number.

Those are digits, ‘-’, ‘.’ and ‘+’. User sometimes could enter any other characters by mistake or with malicious intention.

We must remove those characters before doing any processing. PHP has built-in functions for this purpose. We call it sanitizing.

It will strip off any invalid characters in phone numbers.

This is how you going to do it.

You can see that we have used the filter_var function with a FILTER_SANITIZE_NUMBER_INT constant.

Let’s try this out with few phone numbers.

function validating($phone)< $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number."
"; > validating("202$555*0170");

Output

It strips off the `$` sign and `*` sign and returns only digits. Sometimes you may want to allow `-` in phone numbers. For example, 202-555-0170 is a valid phone number. Let’s see how `filter_var` function reacting to it.

function validating($phone)< $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number."
"; > validating("202-555-0170");

Output

Great again! We get exactly what we want. `filter_var` with `FILTER_SANITIZE_NUMBER_INT` There is one more thing. In international formatting, you need to allow + sign with country code. We have to see does filter_var supports `+` sign.

Let’s take +1-202-555-0170 and see what output does filter_var gives to it.

function validating($phone)< $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number."
"; > validating("+1-202-555-0170");

Output

There is still a small issue. We did not check the lengths of phone numbers yet.

Let’s check the number `2025550170000`.

function validating($phone)< $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number."
"; > validating("2025550170000");

Output

Well, filter_var is not able to validate the length of a phone number. You may want to validate it manually. You can see that the length of a phone number which includes country code could be between 10 and 14. Of course, this length is only valid if we remove ‘-’ in numbers. Let’s do it.

function validating($phone) < $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); $valid_number = str_replace("-", "", $valid_number); if (strlen($valid_number) < 10 || strlen($valid_number) >14) < echo "Invalid Number 
"; > else < echo "Valid Number
"; > > validating("+1-202-555-0170000");

Output

That is our final code. It gives us the expected results. Next, we will see how do we validate phone numbers using Regular Expressions

Читайте также:  Как отключить функцию javascript

Validating Phone Numbers with Regular Expressions

A lot of beginner level developers find regular expression is difficult. Well, actually learning regular expressions is easy. Using it requires good reasoning and logic. It gives great flexibility and power to developers. Therefore, Regular Expressions are such an important tool for any developer.

In the simplest form, the phone number is a 10 digits code without any other characters.

You use the following pattern to represent that. You can use `’/^4+$/’` in Regular Expressions to represent that.

PHP provides the `preg_match` function to parse Regular Expressions.

function validating($phone)< if(preg_match('/^2+$/', $phone)) < echo "Valid Email 
"; >else< echo "Invalid Email
"; > >

We will take several valid and invalid phone numbers and see whether our new code provides us with accurate results.

function validating($phone)< if(preg_match('/^8+$/', $phone)) < echo "Valid Email 
"; >else< echo "Invalid Email
"; > > validating("2025550170"); //10 digits valid phone number validating("202555017000"); //12 digits invalid phone number validating("202$555*01"); //10 letters phone number with invalid characters validating("202$555*0170"); //10 digits phone numbers with invalid characters

Output

Valid Email Invalid Email Invalid Email Invalid Email

Great! We get results as we want it. You can see we have covered various possible inputs in the code.

Next, we will try to validate phone numbers with 202-555-0170 format to validate.

We will have to slightly change our regular expression for that.

function validating($phone)< if(preg_match('/^4-1-3$/', $phone)) < echo "Valid Email 
"; >else< echo "Invalid Email
"; > > validating("202-555-0170");

Output

Notice that we have our changed our regular expression to `’/^4-3-1$/` which will strictly look for the `000-000-0000` pattern.

Finally, let’s validate a phone number which has an international code.

Some countries have international code with one number while the other countries include two numbers in their country codes.

So you should be able to take that into account when writing your regular expression.

function validating($phone)< if(preg_match('/^\+6-9-1-1$/', $phone)) < echo "Valid Email 
"; >else< echo "Invalid Email
"; > > validating("+1-202-555-0170"); validating("+91-202-555-0170");

Output

Conclusion

You can see how powerful Regular expressions are from these examples. You can validate any phone number against any format using Regular Expressions. On top of that PHP provides a very easy way to work with them. That’s it for Phone number validation with PHP. I will meet you with another tutorial.

A Z Hasnain Kabir

I am an aspiring software engineer currently studying at the Islamic University of Technology in Bangladesh. My technical skills include Python automation, data science, machine learning, PHP, cURL and more. With a passion for creating innovative solutions, I am dedicated to mastering the art of software engineering and contributing to the technological advancements of tomorrow.

Источник

Оцените статью