Translate custom jQuery validation messages
Asked Answered
H

4

9

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.

Huberty answered 22/9, 2016 at 4:39 Comment(0)
B
18

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/

Breena answered 22/9, 2016 at 15:37 Comment(2)
Thanks for clearing the "lang" thing, I saw it used somewhere and was fooling around this. Anyway I was asking how to define the translations in "messages_es" file, and now i think i have my answer as i will need to override the message to Spanish using this add method. Cheers Mate for proper clarification!!Huberty
Check out all supported languages and translation keys on githubHerr
D
5

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

Damian answered 11/4, 2019 at 7:54 Comment(0)
C
0

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

Censer answered 6/10, 2019 at 7:57 Comment(0)
P
0

My approach was to create validation script files for each language.

$.validator.addMethod("strong_password", function (value, element) {
  let password = value;
  if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[.@#$%&])(.{8,20}$)/
          .test(password))) {
    return false;
  }
  return true;
}, function (value, element) {
  let password = $(element).val();
  if (!(/^(.{8,20}$)/.test(password))) {
    return 'Password must be between 8 to 20 characters long.';
  } else if (!(/^(?=.*[A-Z])/.test(password))) {
    return 'Password must contain at least one uppercase.';
  } else if (!(/^(?=.*[a-z])/.test(password))) {
    return 'Password must contain at least one lowercase.';
  } else if (!(/^(?=.*[0-9])/.test(password))) {
    return 'Password must contain at least one digit.';
  } else if (!(/^(?=.*[.@#$%&])/.test(password))) {
    return "Password must contain special characters from @#$%&.";
  }
  return false;
});

$.validator.addMethod("strong_password", function (value, element) {
  let password = value;
  if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[.@#$%&])(.{8,20}$)/
          .test(password))) {
    return false;
  }
  return true;
}, function (value, element) {
  let password = $(element).val();
  if (!(/^(.{8,20}$)/.test(password))) {
    return 'Le mot de passe doit comporter entre 8 et 20 caractères.';
  } else if (!(/^(?=.*[A-Z])/.test(password))) {
    return 'Le mot de passe doit contenir au moins une majuscule.';
  } else if (!(/^(?=.*[a-z])/.test(password))) {
    return 'Le mot de passe doit contenir au moins une minuscule.';
  } else if (!(/^(?=.*[0-9])/.test(password))) {
    return 'Le mot de passe doit contenir au moins un chiffre.';
  } else if (!(/^(?=.*[.@#$%&])/.test(password))) {
    return  "Le mot de passe doit contenir des caractères spéciaux de @#$%&.";
  }
  return false;
});

and then in the html (I'm working with java ee and ${lang} is a session attribute).

    <script defer src="js/register-script_${lang}.js"></script>
Porter answered 22/6, 2022 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.