Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate custom jQuery validation messages

I have a question to ask regarding jQuery validation plugin.

I have used localisation to change the default language of error messages to be displayed in Spanish, but I cannot find anything regarding custom messages to be translated. Any clues?

for example

I've included the translation file for Spanish, and this is my code:

$('.signup-form').validate({
    lang : 'es',
    rules:{
        tandc : {required : true}
    },
    messages:{
        tandc : {required : "You have to accept terms and conditions to proceed further"}
    }
})

Default messages like "This field is required" etc are appearing in Spanish, now I want to translate the above message to Spanish but I cannot find where and how to define the translated text.

like image 812
Rock Rathore Avatar asked Sep 22 '16 04:09

Rock Rathore


2 Answers

Nothing is "translated" by the plugin. Translation is done manually and then you'd place these new messages into a localization file where they over-ride the default.

There is also no such .validate() option called lang anywhere in this plugin.

To use the localization files simply means including the file as such someplace after you include the plugin...

<script type="text/javascript" src="...path-to/jquery.validation/1.15.0/jquery.validate.js" />
<script type="text/javascript" src="...path-to/jquery-validation/localization/messages_es.js" />

Then all default messages will be in Spanish.

Default messages like "This field is required" etc are appearing in Spanish, now I want to translate the above message to Spanish but I cannot find where and how to define the translated text.

Including the Spanish localization file simply tells the plugin to replace the default messages as defined by the Spanish localization file.

Your messages object over-rides these default messages, so if you want a Spanish message to over-ride the required rule for just a single input field, then you'll need to write that one in Spanish. There is no built-in dynamic translation that can interpret your messages on the fly.

rules:{
    tandc : {
        required : true
    }
},
messages:{
    tandc : {
        required : "Tienes que aceptar los términos y condiciones de seguir avanzando"
    }
}

This is the priority of messages used:

  1. Any text declared for a single field by rule or entire field using the messages object within .validate() or similar method.

  2. If nothing defined in item #1: Over-ride plugin default messages as defined by $.extend( $.validator.messages, {...}). This is how the Localization files work.

  3. If nothing defined in item #2: Default messages (English) as defined by the plugin.


Now if you need to dynamically change any message as defined by the messages object after .validate() has initialized the plugin on your form, you'll have to use the .rules('add') method to over-ride it.

$('[name="foo"]').rules('add', {
    messages: {
        required: "yo! I'm required."
    }
});

DEMO: jsfiddle.net/3fLkf47u/

like image 126
Sparky Avatar answered Nov 10 '22 10:11

Sparky


So i made simple script to translate validation messages based on accepted answer

function translateValidationMessages(currentLang) {
  message = {
    en: {
      required: "Required.",
      remote: "Please fix this field.",
      email: "Wrong email.",
      url: "Please enter a valid URL.",
      date: "Please enter a valid date.",
      dateISO: "Please enter a valid date (ISO).",
      number: "Please enter a valid number.",
      digits: "Please enter only digits.",
      creditcard: "Please enter a valid credit card number.",
      equalTo: "Please enter the same value again.",
      maxlength: $.validator.format("Please enter no more than {0} characters."),
      minlength: $.validator.format("Please enter at least {0} characters."),
      rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
      range: $.validator.format("Please enter a value between {0} and {1}."),
      max: $.validator.format("Please enter a value less than or equal to {0}."),
      min: $.validator.format("Please enter a value greater than or equal to {0}.")
    },
    et: {
      required: "See väli peab olema täidetud.",
      maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."),
      minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."),
      rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."),
      email: "Palun sisestage korrektne e-maili aadress.",
      url: "Palun sisestage korrektne URL.",
      date: "Palun sisestage korrektne kuupäev.",
      dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).",
      number: "Palun sisestage korrektne number.",
      digits: "Palun sisestage ainult numbreid.",
      equalTo: "Palun sisestage sama väärtus uuesti.",
      range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."),
      max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."),
      min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."),
      creditcard: "Palun sisestage korrektne krediitkaardi number."
    }
  };
    console.log("Translating validation messages to: "+currentLang);

  if (currentLang == "et") {
    $.extend($.validator.messages, message.et);
  } else {
    $.extend($.validator.messages, message.en);
  }

And this function can be called when language dropdown is changed for example

 $("#lang").change(function() {
        translateValidationMessages(this.value)
        console.log("Setting language to " + this.value);
      });

Hope this helps someone

like image 32
Mikk Avatar answered Nov 10 '22 12:11

Mikk