Learn
Introduction to PHP Form Validation
Custom Validations

We’ll often find the validations offered by built-in functions like filter_var() to be insufficient. When validating all but the simplest data, we’ll likely need to write our own, custom input validations.

A very common method for validating data is to compare the input to a pattern we define with a regular expression. The PHP preg_match() function takes two string arguments: a pattern string with a regular expression and a subject string to check. It returns 1 if it matches, 0 if it doesn’t, and FALSE if there was an error.

For example, we can use the regular expression /^[(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4}$/ to test for 10-digit North American telephone numbers. It will allow spaces, hyphens, or periods as optional separators as well as optional parentheses around the first three numbers:

$pattern = '/^[(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4}$/'; preg_match($pattern, "(999)-555-2222"); // Returns: 1 preg_match($pattern, "555-2222"); // Returns: 0

Before we test for regular expression matches, we’ll want to make sure the input isn’t too long. Regular expressions checks can take a lot of computing power—one way a bad actor can damage our website is by submitting extremely long inputs, putting strain on our servers. This can slow down or even crash our site!

We can use the built-in PHP strlen() function to check the length of a given input. Ultimately, the acceptable input length is a judgement call for the web engineer. In this example, we chose 100 characters, but some names can be much longer.

$name = "Aisle Nevertell"; $length = strlen($name); if ($length > 2 && $length < 100){ echo "That seems like a reasonable name to me..."; }

Let’s perform some custom validations!

Instructions

1.

Take a look at the code we’ve provided. The donation form we’re presenting to users has three fields: a number <input> to enter a donation amount, a <select> to choose whether a Mastercard or Visa credit card will be used, and a number <input> to enter a credit card number.

Within the PHP, you’ll be writing the logic to check that the credit card number provided matches the expected format for the type of credit card indicated by the user.

If the user has submitted the form, we’ll want to validate their credit card number. We’ve started you off with an if statement that checks if the form has been submitted. We’ve also reassigned a few variables here:

  • The $card_type variable is reassigned from an empty string to the value the user submitted to the "credit" <select> (either "mastercard" or "visa").
  • The $card_num variable is reassigned from an empty string to the value the user submitted to the "card-num" <input> (their credit card number).
  • The $donation_amount variable is reassigned from an empty string to the value the user submitted to the "amount" <input>.

We’ll break this down into a number of smaller tasks. When you feel like you have a handle on the provided code, click the run button to move on.

2.

Inside the if ($_SERVER["REQUEST_METHOD"] == "POST") block right after the provided variable declarations, add an if/else statement. Your if condition should check that the $card_num is less than 100 characters long.

If $card_num is greater than 100 characters, we won’t want to use regular expression checking, therefore, you should simply assign $feedback the value of $error_message.

We’ll add the logic for what to do if $card_num is less than 100 characters in the step—for now, you can leave it empty.

3.

If $card_num is less than 100 characters, we’ll want to provide additional logic:

Mastercard numbers and Visa numbers are formatted differently, so we’ll want to validate them differently. Create an if/else if block. One should handle if the $card_type type is "mastercard" and the other if it’s "visa".

If the $card_type type is "mastercard", the $card_num should adhere to this regular expression pattern: "/5[1-5][0-9]{14}/". Use preg_match() to check that it does. If so, assign $feedback the value of $success_message. If it does not, assign $feedback the value of $error_message.

If the $card_type type is "visa", the $card_num should adhere to this regular expression pattern: "/4[0-9]{12}([0-9]{3})?([0-9]{3})?/". Use preg_match() to check that it does. If so, assign $feedback the value of $success_message. If it does not, assign $feedback the value of $error_message.

That’s a lot of nested conditions! Walk through your code and make sure it’s the logic you intended.

4.

Awesome! Your function should be working as expected. Test it out with some valid and invalid inputs to see if it’s working as expected.

If you want, you can try to deduce what valid inputs are based on the regular expressions, but check out the hint if you want some examples.

Folder Icon

Take this course for free

Already have an account?