How to Block URLs Inside the Form Fields

Introduction

Would you like to block URLs from inside the form fields such as Single Line Text and Paragraph Text form fields? Most spam comes through now with bots trying to add links into your form and using a small PHP script you can add another layer of protection to your form by rejecting any form submission that tries to come through with a URL listed inside your Single Line Text or Paragraph Text form fields. In this tutorial, we’ll walk you through each step on how to prevent URLs from being placed inside these fields.

Creating your form

For our example, we’re going to create a simple contact form for the Name, Email, How Did you Hear About Us (Single Line Text) and Comment (Paragraph Text) fields.

If you need any help creating your form, please see this documentation.

start by creating your form and adding your fields

Adding the code snippet to block URLs

Now it’s time to add the snippet that will block the URLs inside the form.

If you need help in adding snippets to your site, please see this tutorial.

/*
 * Block URLs from inside form on Single Line Text and Paragraph Text form fields
 *
 * @link https://wpforms.com/developers/how-to-block-urls-inside-the-form-fields/
*/
 
function wpf_dev_check_for_urls( $field_id, $field_submit, $form_data ) {

	if( strpos($field_submit, 'http') !== false || strpos($field_submit, 'www.') !== false ) {
		wpforms()->process->errors[ $form_data[ 'id' ] ][ $field_id ] = esc_html__( 'No URLs allowed.', 'wpforms' );
		return;
	} 
	
}
  
add_action( 'wpforms_process_validate_textarea', 'wpf_dev_check_for_urls', 10, 3 );
add_action( 'wpforms_process_validate_text', 'wpf_dev_check_for_urls', 10, 3 );

This snippet is automatically applied to all forms and will prevent any regular text field or text area field (such as Paragraph Text) from allowing URLs to be entered inside the field.

block urls inside the form with this PHP script

And that’s it! Would you like to also block profanity on these fields? Take a look at our article on How to Block Form Submissions Containing Profanity.

Action References: