1. Home
  2. Snippets
  3. Change validation messages for WPML languages

Change validation messages for WPML languages

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

In WPForms, validation messages are displayed inline as fields are validated “on the fly” using javascript. Using a bit of PHP and javascript these messages can be changed. In some cases, like when using WPML, these messages may need to be conditionally different.

The WPML plugin provides a constant that can be checked to detect the current language of a page. That constant is ICL_LANGUAGE_CODE and more can be read about that in the WPML API documentation.

We can use that constant to check and see if the validation message should be changed. Below is an example that changes the required field validation message depending on the language WPML is using.

/**
 * Customize strings for WPForms form validation, if needed, depending on
 * the language WPML is using.
 * 
 */
function wpf_dev_validation_strings() {

	if ( defined( 'ICL_LANGUAGE_CODE' ) && 'fr' == ICL_LANGUAGE_CODE ) {
		// French
		?>
		<script type="text/javascript">
		jQuery.extend(jQuery.validator.messages, {
			required: "Ce champ est requis."
		});
		</script>
		<?php
	} elseif ( defined( 'ICL_LANGUAGE_CODE' ) && 'es' == ICL_LANGUAGE_CODE )  {
		// Spanish
		?>
		<script type="text/javascript">
		jQuery.extend(jQuery.validator.messages, {
			required: "Este campo es requerido."
		});
		</script>
		<?php
	}
	// Otherwise use default english messages
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_validation_strings', 20 );
Updated on November 20, 2017

Was this article helpful?