I’m new to custom functions in PHP. I’m using the following function, from a book, to validate email addresses:
<?php
$email = $_POST['email'];
function is_email($email) {
// Checks for proper email format
if (!preg_match('/^[A-Za-z0-9!#$%&\'*+-/=?ˆ_`{|}~]+@[A-Za-z0-9]+(\.[A-Za-z0-9]+)+[A-Za-z]%/', $email))
{
return false;
}
else
{
return true;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Validate Email</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email<input type="text" name="email"></input>
<input type="submit" value="Send">
</form>
</body>
</html>
Now, I want to show a message if the email was correct, and show a message if it wasn’t correct. I don’t really know know what to do next. I’ve already tried the following, before the ?> closing tag:
if (is_email($email) == true) {
echo "Right";
}
elseif (is_email($email) == false) {
echo "Wrong";
}
But this doesn’t do anything. What’s the solution for this?
We’ll I’m not 100% sure what exactly is causing your issues here, but allow me to provide another way to validate emails within a custom function. You really don’t have to re-invent the wheel because there is already a native PHP method to validate emails.
I’m using the
filter_var()method here with aFILTER_VALIDATE_EMAIL.