1. Home
  2. Snippets
  3. Customize validation messages for a single form

Customize validation messages for a single form

Heads up!

This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

Dismiss

Validation messages help the user to easily see if they’ve missed a required field or if there’s a formatting issue in certain field types.

Validation message example in WPForms

Using built-in options, you can easily customize these messages at a global level. If you’d like to add a unique set of validation messages to a form, however, you can use the code below.

After adding this code to your site, be sure to adjust the form ID number on Line 25. Then, modify the message content how you’d like.

/**
 * Customize validation messages for a single form—é
 *
 * @param array $strings
 *
 * @return array $strings
 *
 * Note: This snippet will work as expected only when 1 form is on the page (for additional forms, modify regex).
 */
add_filter( 'wpforms_frontend_strings', function( $strings ) {
	global $post;

	if ( ! isset( $post->post_content ) ) {
		return $strings;
	}

	preg_match( '~\[wpforms id=\"(\d+)\"~', $post->post_content, $matches );

	if ( ! is_array( $matches ) || ! isset( $matches[1] ) ) {
		return $strings;
	}

	$form_id = (int) $matches[1];

	if ( $form_id === 10 ) { // Change to your form's ID
		// Below are default validation messages - change as needed.
		$strings['val_required'] = 'This field is required.';
		$strings['val_url'] = 'Please enter a valid URL.';
		$strings['val_email'] = 'Please enter a valid email address.';
		$strings['val_number'] = 'Please enter a valid number.';
		$strings['val_confirm'] = 'Field values do not match.';
		$strings['val_fileextension'] = 'File type is not allowed.';
		$strings['val_filesize'] = 'File exceeds max size allowed.';
		$strings['val_time12h'] = 'Please enter time in 12-hour AM/PM format (eg 8:45 AM).';
		$strings['val_time24h'] = 'Please enter time in 24-hour format (eg 22:45).';
		$strings['val_requiredpayment'] = 'Payment is required.';
		$strings['val_creditcard'] = 'Please enter a valid credit card number.';
	}

	return $strings;
} );
Updated on February 2, 2018

Was this article helpful?