How to Validate a Social Media URL Field in Your Form

Overview

Do you want to add URL fields to your form that would capture social media links? If you have URL fields in your form specifically for each popular social network and you want to make sure they’ve entered the correct social link, you can provide a specific form of validation for the field for that social network. In this tutorial, we’ll show you the code snippet needed to validate the specific social media URL field on your form.

Setup

In our example, we’re building a registration form for our users so we want to use their social media links for their profile page.

To start, we’ll add two URL fields to our form. One will be for Facebook and the other for Twitter.

Add 2 URL fields to your form.  1 for Twitter and 1 for Facebook

Now that you’ve added the fields, it’s time to add the code snippet to your site.

/**
 * Confirm the correct social network link in profile.
 *
 * @link   https://wpforms.com/developers/how-to-validate-a-social-media-url-field-in-your-form/
 *
 */
function wpf_dev_process_check_social_url( $fields, $entry, $form_data ) {
      
    // Optional, you can limit to specific forms. Below, we restrict output to
    // form #902.
    if ( absint( $form_data['id'] ) !== 902 ) {
        return $fields;
    }
    
	
	$fb_url = $fields[7]['value'];
	$findfb   = 'facebook.com';
	$find_fb_url = strpos($fb_url, $findfb);
	if ($find_fb_url === false) {
            // Check the field ID 7 to make sure it contains facebook.com
               wpforms()->process->errors[ $form_data['id'] ] [ '7' ] = esc_html__( 'Please enter a valid Facebook Profile URL.', 'plugin-domain' );
  
        }
	
	$twitter_url = $fields[8]['value'];
	$findtwitter   = 'twitter.com';
	$find_twitter_url = strpos($twitter_url, $findtwitter);
	if ($find_twitter_url === false) {
            // Check the field ID 8 to make sure it contains twitter.com
               wpforms()->process->errors[ $form_data['id'] ] [ '8' ] = esc_html__( 'Please enter a valid Twitter Profile URL.', 'plugin-domain' );
  
        }
	
    }
add_action( 'wpforms_process', 'wpf_dev_process_check_social_url', 10, 3 );

In the code snippet above, we’re only using this snippet on the form ID 902 and only on field 7 which is the Facebook URL field and field 8 which is the Twitter URL field.

When the users enter a link in those fields that do not match what is listed in our code snippet above, they will see an error after they’ve submitted the form.

Now if they users enter a social media URL that doesn't pass through validation, they'll see an error on the page and the form will not be submitted.

And that’s it! You’ve successfully added specific field social URL validation. Would you like to also have the users automatically log in once they’ve completed the registration form? Take a look at our article on How to Automatically Log in Users After Registration.

Action Reference: wpforms_process