Friday, May 24, 2013

How to handle multilingual error messages for jQuery validation plugins

In How to customize error messages for jQuery validation plugin guides us customize error messages for jQuery validation plugin.
But nowadays, multilingual is a requirement for most of the application.
Thus on top of customized messages, we need to provide multilingual support for the error messages.

This article will show an easy way to provide multilingual support for jQuery validation plugin.

The trick is to keep our customized error messages in resource bundle.

Steps:
1.  write the customized error messages in our application's resource bundle. eg, messages.properties
e.g.
invalid_email=Invalid email format


2. use the resource key for the customized error message
 <script>
  $(document).ready(function(){
    $("#myform").validate({
  rules: {
      'myform:emailAddr': {
      required: true,
      email: true
    }
  },
  messages: {
      'myform:emailAddr': {
        email: "#{msgs.invalid_email}"
    }
  }
});
  });
  </script>

3. prepare the resource bundle in different languages, eg. messages_fr.properties, messages_zh.properties, etc.

4. when system locale changed, it will automatically retrieve the messages from appropriate resource bundle.



Done!!


5 comments:

  1. This doesn't work is the script is located in a separate JS file. It outputs it as string. Any ideas?

    ReplyDelete
    Replies
    1. Sorry, I do not get your problem, can you explain in more details.

      Delete
    2. Hi Kian,

      Sorry had a typo and could not edit what I wrote.

      I meant to say that putting the resource key "#{msgs.invalid_email}" for the message doesn't render it properly on the browser as "Invalid email format" instead, it's rendering it as a string, so when the validation kicks in. It reads is as "#{msgs.invalid_email}" on the browser and not "Invalid email format".

      I have the script as a separate Javascript file and not within the HTML page.

      Delete
    3. Hi John Mark,

      When I moved the javascript into a separate js file as you said, I had the same problem.
      I have no ideas at the moment how to resolve this issue as well.

      Delete
    4. Please update this blog post when you do find the solution. I find your site a great resource! :)

      Delete

LinkWithin

Related Posts Plugin for WordPress, Blogger...