PHP : Forms - Validate E-mail and URL

Validating email addresses and URLs in PHP forms is crucial to ensure that the data submitted by users is in the correct format. PHP provides built-in functions and filters to perform email and URL validation. Here's how you can validate email addresses and URLs in PHP forms:

1. Email Validation:

You can use the filter_var() function with the FILTER_VALIDATE_EMAIL filter to validate email addresses.


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];

    if (empty($email)) {
        echo "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
    } else {
        // Email is valid, proceed with further processing
    }
}

 

2. URL Validation:

For URL validation, you can use the filter_var() function with the FILTER_VALIDATE_URL filter.


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $url = $_POST['url'];

    if (empty($url)) {
        echo "URL is required.";
    } elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
        echo "Invalid URL format.";
    } else {
        // URL is valid, proceed with further processing
    }
}

 

Combining Validation:

You can combine email and URL validation with other form validations to ensure that all required fields are correctly filled out.


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $url = $_POST['url'];

    $errors = array(); // Array to store validation errors

    // Validate email
    if (empty($email)) {
        $errors['email'] = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = "Invalid email format.";
    }

    // Validate URL
    if (empty($url)) {
        $errors['url'] = "URL is required.";
    } elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
        $errors['url'] = "Invalid URL format.";
    }

    // Check if there are any validation errors
    if (count($errors) > 0) {
        // There are validation errors, display them to the user
        foreach ($errors as $error) {
            echo $error . "
";
        }
    } else {
        // Form data is valid, proceed with further processing
    }
}

 

By validating email addresses and URLs in your PHP forms, you ensure that the data submitted by users meets the required format, helping to maintain data integrity and improve the user experience.