Mi Lu Mi Lu - 5 months ago 66
Javascript Question

jQuery Validation dynamic change language error messages when changing `mylocale`

In my home page I can change language:

href="home?mylocale=en"
or
href="home?mylocale=ru"
. I use jQuery validate with email and password input. When I add
<script src="resources/assets/js/messages_ru.min.js"></script>
all messages are translated to the Russian, but I want to translate default language error messages only when I choose
href="home?mylocale=ru"
. How to do it?

Answer

Combining two other SO answers can do what you want:

  1. Parse and analyse window.location to see if mylocale is set to ru (from this answer)
  2. Load the script dynamically (from this one)

The result will be (in a <script> tag):

function getParameter(paramName) {

    var searchString = window.location.search.substring(1),
        i, val, params = searchString.split("&");

    for (i=0; i<params.length; i++) {
        val = params[i].split("=");
        if (val[0] == paramName) {
            return val[1];
        }
    }
    return null;
}


if (getParameter("mylocale") == "ru") 
    $.getScript("resources/assets/js/messages_ru.min.js");

A slightly modified version can be used to load any language:

var loc = getParameter("mylocale");
if (loc != null) 
    $.getScript("resources/assets/js/messages_"+loc+".min.js");