How to Change Validation Messages for WPML

Introduction

Would you like to use WPML to change validation messages on your forms? In WPForms, these messages are displayed inline and fields are validated on the fly using PHP. These messages can be easily changed inside your WPForms Settings but if you have a multi lingual site, you may need to have these changed based on the language that the user is currently using.

When you need to provide multiple different language translations, these messages need to be conditionally different.

With that in mind, there is a filter that can be used to check the language your visitor currently is using.  That filter is wpml_current_language.

We can use this filter to check and see if the validation message should be changed.

In this tutorial, we’ll show you the correct code snippets for using WPML and Polylang.

Each code example is going to show you the French and Spanish translations, you’ll need to adjust each code snippet for your correct language as well as the translations.

Remember you’ll need to add the correct code snippets to your site before you will see any changes.

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

Using WPML to change the required field message

Below is an example that changes the required field validation message depending on the language WPML is using.

/**
 * Customize strings for WPForms form validation depending on
 * the language WPML is using.
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 *
 */

function wpforms_dev_frontend_strings( $strings ) {

	$currentLanguage = apply_filters( 'wpml_current_language', false );

	switch ( $currentLanguage ) {
		case 'fr':
			$strings[ 'val_required' ] = 'Ce champ est requis.';
			break;
		case 'es':
			$strings[ 'val_required' ] = 'Este campo es requerido.';
			break;
	}

	return $strings;
}

add_filter( 'wpforms_frontend_strings', 'wpforms_dev_frontend_strings', 20, 1 );

Using Polylang to change the required field message

When using Polylang, you’ll need to use JavaScript instead of PHP.

/**
 * Customize strings for WPForms form validation depending on
 * the language Polylang is using.
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 *
 */

function wpf_dev_validation_strings() {
 
    if ( defined( 'ICL_LANGUAGE_CODE' ) && 'fr' == ICL_LANGUAGE_CODE ) {

        // French
        ?>

        <script type="text/javascript">

        jQuery(document).ready(function() {
            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(document).ready(function() {
            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 );

Changing the other validation messages with WPML

For a complete code snippet for all of the validation messages using WPML, you would use this code.

/**
 * Customize strings for WPForms form validation depending on
 * the language WPML is using.
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 *
 */

function wpforms_dev_frontend_strings( $strings ) {

$currentLanguage = apply_filters( 'wpml_current_language', false );

    switch ( $currentLanguage ) {
            
    //For French translation
    case 'fr':

        //Required field
        $strings[ 'val_required' ] = 'Ce champ est requis.';

        //Valid URL
        $strings[ 'val_url' ] = 'Veuillez saisir une URL valide.';

        //Valid Email
        $strings[ 'val_email' ] = 'Veuillez entrer une URL valide.';

        //Email suggestion text
        $strings[ 'val_email_suggestion' ] = 'Voulez-vous dire {suggestion}?';

        //Valid number
        $strings[ 'val_number' ] = 'S'il vous plait, entrez un nombre valide.';

        //Confirmation message 'fields do not match'
        $strings[ 'val_confirm' ] = 'Les valeurs de champ ne correspondent pas.';

        //Checkbox option limit
        $strings[ 'val_checklimit' ] = 'Vous avez dépassé le nombre de sélections autorisées: {#}.';

        //Valid file type
        $strings[ 'val_extension' ] = 'Le type de fichier n'est pas autorisé.';

        //Max size limit text
        $strings[ 'val_maxsize' ] = 'Le fichier dépasse la taille maximale autorisée.';

        //Valid 12h time format
        $strings[ 'val_time12h' ] = 'Veuillez entrer l'heure au format 12 heures AM / PM (par exemple, 8h45)';

        //Valid 24h time format
        $strings[ 'val_time24h' ] = 'Veuillez entrer l'heure au format 24 heures (par exemple, 22h45).';

        //Payment required text
        $strings[ 'val_requiredpayment' ] = 'Le paiement est requis.';

        //Valid credit card number
        $strings[ 'val_creditcard' ] = 'Veuillez entrer un numéro de carte de crédit valide.';

        //Maximum size limit reached text
        $strings[ 'val_post_max_size' ] = 'La taille totale des fichiers sélectionnés {totalSize} Mo dépasse la limite autorisée {maxSize} Mo.';

        //Valid unique value required
        $strings[ 'val_validation_unique' ] = 'La valeur doit être unique.';

        //All phone field - Smart, International and US
        $strings [ 'val_phone' ] = 'Veuillez fournir un numéro de téléphone valide.';

    break;
    
    //For Spanish translation
    case 'es':

        //Required field
        $strings[ 'val_required' ] = 'Este campo es requerido.';

        //Valid URL
        $strings[ 'val_url' ] = 'Por favor introduzca un URL válido.';

        //Valid Email
        $strings[ 'val_email' ] = 'Por favor, introduce una dirección de correo electrónico válida.';

        //Email suggestion text
        $strings[ 'val_email_suggestion' ] = '¿Quiso decir {sugerencia}?';

        //Valid number
        $strings[ 'val_number' ] = 'Por favor ingrese un número valido.';

        //Confirmation message 'fields do not match'
        $strings[ 'val_confirm' ] = 'Los valores de campo no coinciden.';

        //Checkbox option limit
        $strings[ 'val_checklimit' ] = 'Ha excedido el número de selecciones permitidas: {#}.';

        //Valid file type
        $strings[ 'val_extension' ] = 'El tipo de archivo no está permitido.';

        //Max size limit text
        $strings[ 'val_maxsize' ] = 'El archivo excede el tamaño máximo permitido.';

        //Valid 12h time format
        $strings[ 'val_time12h' ] = 'Ingrese la hora en formato AM / PM de 12 horas (por ejemplo, 8:45 AM).';

        //Valid 24h time format
        $strings[ 'val_time24h' ] = 'Ingrese la hora en formato de 24 horas (por ejemplo, 22:45).';

        //Payment required text
        $strings[ 'val_requiredpayment' ] = 'Se requiere pago.';

        //Valid credit card number
        $strings[ 'val_creditcard' ] = 'Por favor, introduzca un número de tarjeta de crédito válida.';

        //Maximum size limit reached text
        $strings[ 'val_post_max_size' ] = 'El tamaño total de los archivos seleccionados {totalSize} Mb excede el límite permitido {maxSize} Mb.';

        //Valid unique value required
        $strings[ 'val_validation_unique' ] = 'El valor debe ser único.';

        //All phone field - Smart, International and US
        $strings[ 'val_phone' ] = 'Por favor forneça um número de telefone válido.';

    break;
    }

return $strings;

}

add_filter( 'wpforms_frontend_strings', 'wpforms_dev_frontend_strings', 20, 1 );

Changing the other validation messages with Polylang

For a complete code snippet for all of the validation messages using Polylang, you would use this code.

/**
 * Customize strings for WPForms form validation depending on
 * the language Polylang is using.
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 *
 */

function wpf_dev_validation_strings() {
 
    if ( defined( 'ICL_LANGUAGE_CODE' ) && 'fr' == ICL_LANGUAGE_CODE ) {

        // French
        ?>

        <script type="text/javascript">

        jQuery(document).ready(function() {
            jQuery.extend(jQuery.validator.messages, {
                required: "Ce champ est requis.",
                url: "Please enter a valid URL.",
                email: "Veuillez entrer une URL valide.",
                email_suggestion: "Voulez-vous dire {suggestion}?",
                number: "S'il vous plait, entrez un nombre valide.",
                confirm: "Les valeurs de champ ne correspondent pas.",
                checklimit: "Vous avez dépassé le nombre de sélections autorisées: {#}.",
                extension: "Le type de fichier n'est pas autorisé.",
                maxsize: "Le fichier dépasse la taille maximale autorisée.",
                time12h: "Veuillez entrer l'heure au format 12 heures AM / PM (par exemple, 8h45).",
                time24h: "Veuillez entrer l'heure au format 24 heures (par exemple, 22h45).",
                requiredpayment: "Le paiement est requis.",
                creditcard: "Veuillez entrer un numéro de carte de crédit valide.",
                post_max_size: "La taille totale des fichiers sélectionnés {totalSize} Mo dépasse la limite autorisée {maxSize} Mo.",
                validation_unique: "La valeur doit être unique.",
                'us-phone-field':    "Veuillez fournir un numéro de téléphone valide",
                'int-phone-field':   "Veuillez fournir un numéro de téléphone valide",
                'smart-phone-field': "Veuillez fournir un numéro de téléphone valide",
            });
        });

        </script>

        <?php
    } elseif ( defined( 'ICL_LANGUAGE_CODE' ) && 'es' == ICL_LANGUAGE_CODE )  {

        // Spanish
        ?>

        <script type="text/javascript">

        jQuery(document).ready(function() {
            jQuery.extend(jQuery.validator.messages, {
                required: "Este campo es requerido.",
                url: "Por favor introduzca un URL válido.",
                email: "Por favor, introduce una dirección de correo electrónico válida.",
                email_suggestion: "¿Quiso decir {sugerencia}?",
                number: "Por favor ingrese un número valido.",
                confirm: "Los valores de campo no coinciden.",
                checklimit: "Ha excedido el número de selecciones permitidas: {#}.",
                extension: "El tipo de archivo no está permitido.",
                maxsize: "El archivo excede el tamaño máximo permitido.",
                time12h: "Ingrese la hora en formato AM / PM de 12 horas (por ejemplo, 8:45 AM).",
                time24h: "Ingrese la hora en formato de 24 horas (por ejemplo, 22:45).",
                requiredpayment: "Se requiere pago.",
                creditcard: "Por favor, introduzca un número de tarjeta de crédito válida.",
                post_max_size: "El tamaño total de los archivos seleccionados {totalSize} Mb excede el límite permitido {maxSize} Mb.",
                validation_unique: "El valor debe ser único.",
                'us-phone-field':    "Por favor forneça um número de telefone válido.",
                'int-phone-field':   "Por favor forneça um número de telefone válido.",
                'smart-phone-field': "Por favor forneça um número de telefone válido.",
            });
        });

        </script>

        <?php
    }

    // Otherwise use default English messages

}

add_action( 'wpforms_wp_footer_end', 'wpf_dev_validation_strings', 20 );

That is how easy it is to change validation messages in WPForms using WPFML or Polylang

And that’s it! You can now successfully change the validation messages. Would you like to change the date picker strings to match the language as well? Take a look at our article on How to Modify Date Field Date Picker Strings.