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.
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:
Any text declared for a single field by rule or entire field using the messages
object within .validate()
or similar method.
If nothing defined in item #1: Over-ride plugin default messages as defined by $.extend( $.validator.messages, {...})
. This is how the Localization files work.
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/