search ]

Restrict Free Emails in HTML Forms and Contact Form 7

Allowing only corporate emails in forms can be a crucial step for businesses that want to avoid submissions from free email providers like Gmail, Yahoo, or Outlook. This ensures that the users submitting the form are associated with a business or organization.

In this guide, you’ll learn how to enforce this restriction in standard HTML forms and in the popular WordPress plugin, Contact Form 7 (CF7).

Why Restrict Free Email Providers?

Restricting free email providers can improve the reliability and quality of the submissions you receive. It ensures they come from professional users associated with organizations or businesses.

  • Professionalism: Corporate emails often reflect a professional identity associated with a company.
  • Spam Reduction: Limiting free email domains reduces the likelihood of receiving spam submissions.
  • Enhanced Data Quality: You can gather more relevant and actionable data from genuine corporate users.
  • Lead Quality: For B2B companies, corporate emails help filter out casual signups and focus on qualified leads.

Common Free Email Domains to Block

Before implementing any validation, you need a solid list of free email providers to block. The most common ones include:

const restrictedDomains = [
    'gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com',
    'aol.com', 'protonmail.com', 'proton.me', 'icloud.com',
    'mail.com', 'zoho.com', 'yandex.com', 'gmx.com',
    'tutanota.com', 'tuta.com', 'live.com', 'msn.com'
];

You can expand this list based on your needs. The examples in this post use a shorter list for clarity, but in production you should include as many free providers as possible.

Restricting Free Emails in an HTML Form

To restrict free email providers in a standard HTML form, you can use JavaScript to validate the email field before submission.

HTML Code

Here is a basic form with an email input:

<form id="corporate-email-form">
    <label for="email">Enter your corporate email:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">Submit</button>
</form>

JavaScript Code

This script listens for the form’s submit event and checks the email domain against a restricted list:

document.getElementById('corporate-email-form').addEventListener('submit', function (e) {
    const emailField = document.getElementById('email');
    const emailValue = emailField.value.trim();
    const restrictedDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com'];

    const domain = emailValue.split('@')[1]?.toLowerCase();
    if (restrictedDomains.includes(domain)) {
        e.preventDefault();
        alert('Please use a corporate email address.');
    }
});

The script extracts the domain from the entered email address and checks if it matches any restricted domains. If it does, the form submission is prevented and an alert notifies the user.

Client-side JavaScript validation can be bypassed by disabling JavaScript in the browser or by submitting the form data directly. Always pair client-side checks with server-side validation to ensure restricted emails are truly blocked.

Using the HTML5 Pattern Attribute

You can also use the native HTML5 pattern attribute on the email input for basic browser-level validation. This approach provides instant feedback without any JavaScript:

<input
    type="email"
    id="email"
    name="email"
    pattern="^[a-zA-Z0-9._%+-]+@(?!gmail.com$|yahoo.com$|outlook.com$|hotmail.com$)[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"
    title="Please use a corporate email address, not a free provider like Gmail or Yahoo."
    required
>

The pattern attribute uses a regex that rejects emails from the listed free providers. The title attribute provides a custom tooltip message when validation fails.

Note that the pattern attribute alone is not a security measure. It is a UX enhancement that works alongside JavaScript and server-side validation.

Using Regex for Advanced Validation

For more advanced validation, you can use a regex pattern to dynamically exclude specific domains.

JavaScript Code with Regex

This approach uses a negative lookahead to reject free email domains in a single regex test:

const emailRegex = /^[a-zA-Z0-9._%+-]+@(?!gmail.com$|yahoo.com$|outlook.com$|hotmail.com$)[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;

document.getElementById('corporate-email-form').addEventListener('submit', function (e) {
    const emailField = document.getElementById('email');
    const emailValue = emailField.value.trim();

    if (!emailRegex.test(emailValue)) {
        e.preventDefault();
        alert('Please use a corporate email address.');
    }
});

This regex ensures the email domain does not match any restricted domains. It validates the input in a single step and prevents submission if a free email is detected.

“Using a regular expression (regex) for email validation provides a robust way to enforce custom rules, ensuring your form accepts only the desired types of email addresses.”

Restricting Free Emails in Contact Form 7

While Contact Form 7 doesn’t directly support the pattern attribute, you can enforce corporate email validation by using the wpcf7_validate_email filter for server-side validation or JavaScript for client-side validation.

If you’re also looking to prevent spam in Contact Form 7 using Akismet, combining both approaches gives you a strong defense against low-quality submissions.

Using the wpcf7_validate_email Filter

Contact Form 7 provides the wpcf7_validate_email and wpcf7_validate_email* filters, allowing you to validate email fields server-side during form submission. The asterisk version targets required email fields.

Here is how you can restrict free email domains:

function validate_corporate_email_field( $result, $tag ) {
    // Target only the "corporate-email" field
    if ( $tag->name !== 'corporate-email' ) {
        return $result;
    }

    $restricted_domains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com'];

    $email = isset( $_POST['corporate-email'] ) ? sanitize_email( wp_unslash( $_POST['corporate-email'] ) ) : '';
    $domain = strtolower( substr( strrchr( $email, '@' ), 1 ) );

    if ( in_array( $domain, $restricted_domains, true ) ) {
        // Prevent submission and display message in .wpcf7-response-output
        $result->invalidate( $tag, 'Please use a corporate email address.' );
    }

    return $result;
}
add_filter( 'wpcf7_validate_email*', 'validate_corporate_email_field', 20, 2 );

This code specifically targets an email field with the name corporate-email. Make sure your CF7 form includes an input like this:

[email* corporate-email placeholder "email@yourcompany.com*"]

“Using the field name corporate-email ensures the validation filter runs only on that specific input, allowing you to customize behavior without affecting other email fields.”

For better performance on sites with multiple forms, consider optimizing Contact Form 7 so its assets only load on pages that actually use forms.

Client-Side Validation with JavaScript

In addition to server-side validation, you can also prevent submission on the client side using JavaScript. This provides instant feedback to the user:

document.addEventListener('DOMContentLoaded', function () {
    const form = document.querySelector('.wpcf7 form');

    if (form) {
        form.addEventListener('submit', function (e) {
            const emailField = form.querySelector('input[name="corporate-email"]');
            const emailValue = emailField.value.trim();
            const restrictedDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com'];

            if (emailValue.includes('@')) {
                const domain = emailValue.split('@')[1].toLowerCase();

                if (restrictedDomains.includes(domain)) {
                    alert('Please use a corporate email address.');
                    e.preventDefault(); // This stops CF7 from submitting
                }
            }
        });
    }
});

This script targets only the corporate-email input field using input[name="corporate-email"]. It prevents the form from being submitted if a restricted domain is detected.

“Combining server-side and client-side validation gives you the best of both worlds: security and user experience.”

Note: If you’re using HubSpot forms or have HubSpot tracking enabled, be aware that form submissions may still be captured on their end, even if the client-side JavaScript prevents the actual CF7 submission. This can lead to partial or duplicate data collection in HubSpot.

FAQs

Common questions about restricting free emails in forms:

Can users bypass client-side email validation?
Yes. Client-side validation using JavaScript or the HTML5 pattern attribute can be bypassed by disabling JavaScript or submitting form data directly. Always implement server-side validation as well to ensure restricted emails are truly blocked.
What is the difference between wpcf7_validate_email and wpcf7_validate_email*?
The wpcf7_validate_email filter targets optional email fields, while wpcf7_validate_email* targets required email fields (those defined with an asterisk in the CF7 form tag). If your email field is required, use the asterisk version.
How do I add more free email domains to the blocked list?
Simply add the domain to the restrictedDomains array in JavaScript or the $restricted_domains array in PHP. Common additions include protonmail.com, proton.me, aol.com, icloud.com, zoho.com, yandex.com, and mail.com.
Will this validation work with other form plugins like WPForms or Gravity Forms?
The HTML and JavaScript examples work with any form, regardless of the plugin. However, the PHP filter using wpcf7_validate_email* is specific to Contact Form 7. Other plugins like WPForms and Gravity Forms have their own validation hooks and APIs.
Should I use the HTML5 pattern attribute or JavaScript for email domain validation?
Ideally, use both. The HTML5 pattern attribute provides instant browser-native feedback without any JavaScript. JavaScript validation gives you more control over the error message and user experience. Together with server-side validation, they form a complete validation strategy.

Conclusion

Restricting free email providers in forms is a straightforward yet effective way to ensure better-quality submissions. Whether you’re using a simple HTML form or the Contact Form 7 plugin, these methods allow you to enforce corporate email usage seamlessly.

For the strongest protection, combine client-side validation (JavaScript and the HTML5 pattern attribute) with server-side validation. This ensures that restricted emails are blocked even if a user bypasses the front-end checks.

Feel free to adapt the examples provided to fit your specific requirements. If you have any questions or need further assistance, share them in the comments below!

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo