We have covered Validation of HTML Form & now let’s see validation in e-mails and URL
To validate an email address in PHP, you can use a combination of the ‘filter_var’ function and the ‘FILTER_VALIDATE_EMAIL’ filter.
<?php
function isValidEmail($email) {
// Use FILTER_VALIDATE_EMAIL filter
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
?>
<?php
// Example usage
$email = "user@example.com";
if (isValidEmail($email)) {
echo "Valid email address";
} else {
echo "Invalid email address";
}
?>
<?php
function isValidEmail($email) {
// Use preg_match to test the email against the pattern
return preg_match( "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email) === 1;
}
?>
The code below shows a simple way to check if the URL address is valid or not by using php predefined function ‘filter_var’.
<?php
function isValidUrl($url) {
// Use FILTER_VALIDATE_URL filter
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
?>
<?php
$url = "http://www.example.com";
if (isValidUrl($url)) {
echo "Valid URL";
} else {
echo "Invalid URL";
}
?>
<?php
function isValidEmail($email) {
// Use preg_match to test the email against the pattern
return preg_match( "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email) === 1;
}
?>