PHP Form URL/E-mail Validation

Validating email addresses and website URLs

๐Ÿ“ง What is URL/Email Validation?

URL and email validation ensures users enter properly formatted web addresses and email addresses. This prevents errors and maintains data quality in your application's database.


<?php
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email!";
}
?>
                                    

Validation Methods

๐Ÿ“ง

Email Filter

Built-in email validation

<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid";
}
?>
๐ŸŒ

URL Filter

Built-in URL validation

<?php
$url = "https://example.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo "Valid";
}
?>
๐Ÿ”

Regex Pattern

Custom validation patterns

<?php
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    echo "Valid";
}
?>
๐Ÿงน

Sanitization

Clean input before validation

<?php
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$url = filter_var($url, FILTER_SANITIZE_URL);
?>

๐Ÿ”น Email Validation Example

Validate email addresses using PHP's filter_var function:

<?php
$email = "";
$emailErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = $_POST["email"];
        
        // Remove illegal characters
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        
        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
}
?>

<form method="post">
    Email: <input type="text" name="email" value="<?php echo $email; ?>">
    <span style="color:red;">* <?php echo $emailErr; ?></span>
    <br><br>
    <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($emailErr)) {
    echo "<p>Valid email: " . htmlspecialchars($email) . "</p>";
}
?>

๐Ÿ”น URL Validation Example

Validate website URLs to ensure proper format:

<?php
$website = "";
$websiteErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["website"])) {
        $websiteErr = "Website URL is required";
    } else {
        $website = $_POST["website"];
        
        // Remove illegal characters
        $website = filter_var($website, FILTER_SANITIZE_URL);
        
        // Validate URL
        if (!filter_var($website, FILTER_VALIDATE_URL)) {
            $websiteErr = "Invalid URL format";
        }
    }
}
?>

<form method="post">
    Website: <input type="text" name="website" value="<?php echo $website; ?>">
    <span style="color:red;">* <?php echo $websiteErr; ?></span>
    <br><br>
    <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($websiteErr)) {
    echo "<p>Valid URL: " . htmlspecialchars($website) . "</p>";
}
?>

๐Ÿ”น Combined Email and URL Validation

Validate both email and URL in a single form:

<?php
$email = $website = "";
$emailErr = $websiteErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
    
    // Validate website (optional field)
    if (!empty($_POST["website"])) {
        $website = filter_var($_POST["website"], FILTER_SANITIZE_URL);
        if (!filter_var($website, FILTER_VALIDATE_URL)) {
            $websiteErr = "Invalid URL format";
        }
    }
    
    // Process if no errors
    if (empty($emailErr) && empty($websiteErr)) {
        echo "<p style='color:green;'>Form submitted successfully!</p>";
    }
}
?>

<form method="post">
    Email: <input type="text" name="email" value="<?php echo $email; ?>">
    <span style="color:red;">* <?php echo $emailErr; ?></span>
    <br><br>
    
    Website: <input type="text" name="website" value="<?php echo $website; ?>">
    <span style="color:red;"><?php echo $websiteErr; ?></span>
    <br><br>
    
    <input type="submit" value="Submit">
</form>

๐Ÿ”น Email Validation with Regex

Use regular expressions for custom email validation rules:

<?php
function validateEmail($email) {
    // Basic email pattern
    $pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
    return preg_match($pattern, $email);
}

$email = "[email protected]";

if (validateEmail($email)) {
    echo "Valid email address";
} else {
    echo "Invalid email address";
}

// Examples:
// [email protected] - Valid
// [email protected] - Valid
// user@example - Invalid (no domain extension)
// @example.com - Invalid (no username)
// [email protected] - Invalid (no domain name)
?>

๐Ÿ”น URL Validation with Regex

Custom URL validation to check for specific patterns:

<?php
function validateURL($url) {
    // URL pattern with http/https
    $pattern = "/^(https?:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(\/.*)?$/";
    return preg_match($pattern, $url);
}

$url = "https://www.example.com";

if (validateURL($url)) {
    echo "Valid URL";
} else {
    echo "Invalid URL";
}

// Examples:
// https://example.com - Valid
// www.example.com - Valid
// example.com - Valid
// http://example.com/page - Valid
// example - Invalid (no domain extension)
// https://example - Invalid (no domain extension)
?>

๐Ÿ”น Advanced Email Validation

Check if email domain exists using DNS records:

<?php
function validateEmailDomain($email) {
    // First, check basic format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }
    
    // Extract domain from email
    list($user, $domain) = explode('@', $email);
    
    // Check if domain has MX records (mail server)
    return checkdnsrr($domain, 'MX');
}

$email = "[email protected]";

if (validateEmailDomain($email)) {
    echo "Email address and domain are valid";
} else {
    echo "Invalid email or domain does not exist";
}
?>

๐Ÿ”น Complete Contact Form

Full example with name, email, and website validation:

<?php
$name = $email = $website = "";
$nameErr = $emailErr = $websiteErr = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = htmlspecialchars(trim($_POST["name"]));
    }
    
    // Validate email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
    
    // Validate website (optional)
    if (!empty($_POST["website"])) {
        $website = filter_var($_POST["website"], FILTER_SANITIZE_URL);
        if (!filter_var($website, FILTER_VALIDATE_URL)) {
            $websiteErr = "Invalid URL format";
        }
    }
    
    // If no errors, show success
    if (empty($nameErr) && empty($emailErr) && empty($websiteErr)) {
        $success = "Thank you! Your information has been submitted.";
    }
}
?>

<!DOCTYPE html>
<html>
<body>

<h2>Contact Form</h2>

<?php if ($success): ?>
    <p style="color:green;"><?php echo $success; ?></p>
<?php endif; ?>

<form method="post">
    Name: <input type="text" name="name" value="<?php echo $name; ?>">
    <span style="color:red;">* <?php echo $nameErr; ?></span>
    <br><br>
    
    Email: <input type="text" name="email" value="<?php echo $email; ?>">
    <span style="color:red;">* <?php echo $emailErr; ?></span>
    <br><br>
    
    Website: <input type="text" name="website" value="<?php echo $website; ?>">
    <span style="color:red;"><?php echo $websiteErr; ?></span>
    <br><br>
    
    <input type="submit" value="Submit">
</form>

</body>
</html>

๐Ÿง  Test Your Knowledge

Which filter validates an email address in PHP?