Learn
Introduction to PHP Form Validation
Basic Validation with filter_var()

We can use the same filter_var() function to validate as well as sanitize! There are a number of provided validation filters, but they work a bit differently from the sanitization filters. If the variable is deemed valid, filter_var() will return it; otherwise, it will return FALSE:

$bad_email = 'fake - at - prank dot com'; if (filter_var($bad_email, FILTER_VALIDATE_EMAIL)){ echo "Valid email!"; } else { echo "Invalid email!"; } // Prints: Invalid email!

It’s worth noting that the provided FILTER_VALIDATE_EMAIL filter is stricter than the guidelines regulating acceptable email addresses. If a site needed to accept non-latin characters, for example, the built-in FILTER_VALIDATE_EMAIL filter wouldn’t be sufficient.

Using the provided validation filters is really convenient. You can check out the list of available validation filters in the PHP manual. For example, FILTER_VALIDATE_URL is useful for checking if a string corresponds to a possible URL.

Let’s practice!

Instructions

1.

Take a minute to familiarize yourself with the provided code. We declared three variables: $validation_error, $user_url, and $form_message:

  • The $user_url is assigned to the value attribute of the "url" input element.
  • The $validation_error is the inner HTML of our error <span>.
  • The $form_message is the inner HTML for the <p> element after the form.

Right now these variables are all assigned empty strings. Notice how when you submit the form, nothing changes. You’ll change that in the next task!

2.

In the PHP section of your code (above the HTML), you’ll be writing code to validate a user’s input and then generate an error or message depending on whether or not their input was valid.

You’ll be reassigning the variables we’ve defined for you ($validation_error, $user_url, and $form_message) depending on the user’s submission.

If the form has been submitted ($_SERVER["REQUEST_METHOD"] === "POST"), you should assign to $user_url the value the user submitted for the "url" input.

You should then validate the $user_url using the filter_var() function and a a validation filter designed to validate URLs. If the form has not been submitted, you shouldn’t do anything.

If the URL is valid, you should assign to $form_message the string value "Thank you for your submission.".

If the URL is not valid, you should assign to $validation_error the string value of "* This is an invalid URL." and $form_message should be assigned the string value "Please retry and submit your form again.".

3.

Check your form with valid and invalid URLs and make sure it’s working properly. Note that a “valid” URL must start with the HTTP protocol (eg. http://).

Folder Icon

Take this course for free

Already have an account?