How to Change Validation Messages for WPML

Introduction

Would you like to use WPML or Polylang 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 ICL_LANGUAGE_CODE. Using this filter means that if you’re using WPML or Polylang for your WordPress translations, you can check what the current language on your site is set to.

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

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.

Changing the standard required field message

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

/**
 * Customize strings for WPForms form validation 
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 */

function wpforms_dev_frontend_strings( $strings ) {

	$currentLanguage = defined( 'ICL_LANGUAGE_CODE' ) ? ICL_LANGUAGE_CODE : null;

	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 );

Changing the other validation messages

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

/**
 * Customize strings for WPForms form validation 
 * 
 * @link https://wpforms.com/developers/change-validation-messages-for-wpml/
 */

function wpforms_dev_frontend_strings( $strings ) {

$currentLanguage = defined( 'ICL_LANGUAGE_CODE' ) ? ICL_LANGUAGE_CODE : null;

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

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

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

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

        // Email restricted text
        $strings[ 'val_email_restricted' ] = 'Cette adresse e-mail n\'est pas autorisée.';

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

        // Valid positive number
        $strings[ 'val_number_positive' ] = 'Veuillez entrer un nombre positif valide.';

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

        // Valid input mask incomplete
        $strings[ 'val_inputmask_incomplete' ] = 'Veuillez remplir le champ au format requis.';

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

        // Character limit
        $strings[ 'val_limit_characters' ] = 'La limite est de {limit} caractères. Caractères restants : {remaining}.';

        // Word limit
        $strings[ 'val_limit_words' ] = 'La limite est de {limit} mots. Mots restant : {restant}.';

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

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

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

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

        // Number of files upload limit text
        $strings[ 'maxfilenumber' ] = 'Les téléchargements de fichiers dépassent le nombre maximum autorisé ({fileLimit}).';

        // 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).';

        // Limit hours text 'Please enter time between...'
        $strings[ 'val_time_limit' ] = 'Veuillez saisir une durée comprise entre {minTime} et {maxTime}.';

        // 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.';

        // Password strength text
        $strings[ 'val_password_strength' ] = 'Un mot de passe plus fort est requis. Envisagez d\'utiliser des lettres majuscules et minuscules, des chiffres et des symboles.';

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

        // reCAPTCHA failed message text
        $strings[ 'val_recaptcha_fail_msg' ] = 'La vérification Google reCAPTCHA a échoué, veuillez réessayer plus tard.';

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

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

        // 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}?';

        // Email Restricted
        $strings[ 'val_email_restricted' ] = 'Esta dirección de correo electrónico no está permitida.';

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

        // Valid positive number
        $strings[ 'val_number_positive' ] = 'Introduzca un número positivo válido.';

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

        // Valid input mask incomplete text
        $strings[ 'val_inputmask_incomplete' ] = 'Por favor llene el campo en el formato requerido.';

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

        // Character limit
        $strings[ 'val_limit_characters' ] = 'El límite es {límite} caracteres. Caracteres restantes: {restante}.';

        // Word limit
        $strings[ 'val_limit_words' ] = 'El límite es {límite} palabras. Palabras restantes: {restante}.';

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

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

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

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

        // Number of files upload limit text
        $strings[ 'maxfilenumber' ] = 'Las cargas de archivos superan el número máximo permitido ({fileLimit}).';

        // 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).';

        // Limit hours text 'Please enter time between...'
        $strings[ 'val_time_limit' ] = 'Ingrese el tiempo entre {minTime} y {maxTime}.';

        // 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.';

        // Password strength text
        $strings[ 'val_password_strength' ] = 'Se requiere una contraseña más fuerte. Considere el uso de letras mayúsculas y minúsculas, números y símbolos.';

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

        // reCAPTCHA failed message text
        $strings[ 'val_recaptcha_fail_msg' ] = 'La verificación de Google reCAPTCHA falló, inténtalo de nuevo más tarde.';

    break;
    }

return $strings;

}

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

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

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.

Action Reference: wpforms_wp_footer_end

Filter Reference: wpforms_frontend_strings