Translate custom jQuery validation messages

可紊 提交于 2020-01-21 07:29:52

问题


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.


回答1:


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/




回答2:


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




回答3:


You can use a jQuery library called abValidate which you can give localized validation error messages.

Example:

$(document).ready(function () {
    $(".ab-form").abValidate({
        color: "#556b2f",
        backgroundColor: "white",
        debug: true
    });
});
<html>
   <head>
      <link rel="stylesheet" href="https://aslamanver.github.io/abvalidate/abValidate.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://aslamanver.github.io/abvalidate/abValidate.min.js"></script>
   </head>
   <body>
      <form class="ab-form" action="#">
         <div class="form-group">
            <input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more"
               name="name" class="ab-validation-i" />
            <div class="error"></div>
         </div>
         <br>
         <div class="form-group">
            <input type="submit" name="submit" value="Submit">
         </div>
      </form>
   </body>
</html>

You just want to write everything in HTML as below once you initialized your for with abValidate library.

<input type="text" name="name" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" class="ab-validation-i" />

abValidate - Github link:
https://github.com/aslamanver/abvalidate

Reference:
https://medium.com/@aslamanver/localized-custom-validation-messages-jquery-2892e021648f



来源:https://stackoverflow.com/questions/39630386/translate-custom-jquery-validation-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!