When using the popular Contact Form 7 plugin for WordPress, you may want to restrict certain types of input in text fields. A common request is to prevent users from submitting URLs or links in specific text or textarea fields. This guide provides a solution for implementing custom validation to achieve this, using PHP code.
Why Prevent URLs in Form Fields?
Restricting URLs in form fields can help:
- Reduce spam: Links are often included in spam messages.
- Ensure data integrity: Avoid unwanted or irrelevant information in certain fields.
- Improve user experience: Guide users to provide the intended type of input.
The Code for Validation
Add the following PHP code to your WordPress site’s functions.php file or a custom plugin. It customizes Contact Form 7’s validation process to block inputs containing URLs
Add filters to validate specific input types in Contact Form 7 – Github Gist
How the Code Works
1. Attach Filters:
- The add_filter function hooks our custom validation function (validate_no_urls) to the validation process of Contact Form 7.
- Filters are applied to text, text*, textarea, and textarea* fields.
2. Validation Logic:
- Retrieves the form field value and skips validation if the field is explicitly for URLs (e.g., type=”url” or name=”url”).
- Looks for disallowed patterns (e.g., http://, https://, www., etc.) in the input.
- If a match is found, the field is marked invalid, and an error message (“URLs are not allowed”) is displayed.
3. Prevent Submission:
- When the input is invalid, the form submission is blocked, and the user is prompted to correct their input.
Customizing the Code
Error Message:
Modify the error message in this line:
$result->invalidate($tag, __('URLs are not allowed', 'contact-form-7'));
Replace “URLs are not allowed” with your custom message, e.g., “Please do not include links.”.
Patterns to Block:
Add or remove patterns in the $not_allowed array:
$not_allowed = ['http://', 'https://', 'www.', '[url', '<a '];
Best Practices
Test Before Deployment
Test the validation on a staging site to ensure it works as expected and doesn’t interfere with other functionality.
Use Specific Field Names:
Avoid applying this validation to fields that may legitimately contain URLs.