PHP Form URL/E-mail

PHP Form Validation: URL and E-mail

Ensuring that a field is not empty is a great start, but it doesn't guarantee the data is useful. If you ask for an email address and the user types "Hello World", the field isn't empty, but it certainly isn't an email!

To solve this, we can use PHP's powerful filter_var() function to validate specific data formats.


Validating an E-mail Address

The easiest and safest way to check whether an email address is well-formed is to use the FILTER_VALIDATE_EMAIL filter.

E-mail Validation Example

<?php
$email = "test@example.com";
$bad_email = "test@example";

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format for first email.\n"; } else { echo "The first email is valid!\n"; }

if (!filter_var($bad_email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format for second email."; } ?>


Validating a URL

Similarly, if your form asks for a website link, you can check if the input is a properly formatted URL using the FILTER_VALIDATE_URL filter.

URL Validation Example

<?php
$website = "https://www.intricatedevo.com";

if (!filter_var($website, FILTER_VALIDATE_URL)) { echo "Invalid URL format"; } else { echo "The URL is perfectly formatted!"; } ?>

Using Regular Expressions (RegEx)

While filter_var is the easiest method, you can also use preg_match() with custom Regular Expressions if you need to validate complex data patterns like a Phone Number or a strict password requirement (e.g., must contain an uppercase letter and a number).


Exercise

?

Which PHP function is utilized to easily validate standard Email and URL formats?