Spring 和 jQuery 验证:如何使用本地化字符串?

Spring and jQuery validation: How to use localized strings?

以这种形式为例:

<form id="login_form" method="post" action="/rest/auth/auth">

    <div id="login_email" class="row margin-top-50">
        <div class="col-md-12" id="input_container">
            <input id="login_email_input" class="input_edit input_edit_img_width" type="email" name="email" th:placeholder="#{label.common_email}"></input>
            <img class="input_edit_img" src="/img/ic_login_user.png"></img>
        </div>
    </div>

    <div id="login_password" class="row margin-top-15">
        <div class="col-md-12" id="input_container">
            <input id="login_password_input" class="input_edit input_edit_img_width" type="password" name="password" th:placeholder="#{label.common_password}"></input>
            <img class="input_edit_img" src="/img/ic_login_pw.png"></img>
        </div>
    </div>

    <div class="row margin-top-15">
        <div class="col-md-12">
            <div class="checkbox_square">
                <input id="check_password_show" type="checkbox" value=""></input>
                <label for="check_password_show"></label>
                <span th:text="#{label.common_password_show}"></span>
            </div>
        </div>
    </div>

    <div class="row margin-top-15">
        <div class="col-md-12">
            <button id="login_submit" type="submit" class="btn btn-default btn-blue" th:text="#{label.login}"></button>
        </div>
    </div>

</form>

如您所见,我正在使用 th:placeholder="#{label.common_email}" 等本地化消息。

我现在想使用 jQuery 验证,我真的需要以某种方式使用我的 messages.properties 中的本地化字符串,如下所示:

$("#login_form").validate({
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true
            /*minlength: 6,
            maxlength: 20*/
        }
    },
    messages: {
        email: {
            required: "#{label.input_missing_email}",
            email: "#{label.input_missing_email_valid}"
        },
        password: {
            required: "#{label.input_missing_password}",
            minlength: "#{label.input_missing_password_valid}"
        }
    }
});

有什么方法可以让我从客户端 javascript 访问我的 spring 本地化消息?或者如果我必须使用本地化的字符串,我应该更好地使用不同的东西来验证吗?

您不需要从 javascript 级别的 messages.properties 中检索您的语言环境字符串, 如果您只将语言环境字符串保留在 HTML 中,您可以轻松地做到这一点, 这是我要做的:

HTML:

  • 在每次输入后单独制作 <span><div>(以防万一 在该元素之后显示一些消息,一些验证类型)
  • <span><div>
  • 中的 html 处保留所有语言环境字符串

JS:

  • 只要show/hide你各自的<span><div>当jQuery为相应的表单输入触发验证时。

jQuery.i18n.properties 是一个轻量级 jQuery 插件,用于从 '.properties' 文件向 javascript 提供国际化,就像在 Java 资源包中一样。它根据提供的语言和国家代码加载和解析资源包 (.properties)。More

假设

label.delete.success =Successfully Deleted
label.delete.failure=Error in success

是您的 messages.properties 属性文件。

然后 jQuery.i18n.prop(label.delete.success) returns Successfully Deleted 来自你的 javascript 文件。

希望对您有所帮助。