我正在一个有2种语言的项目中工作,我使用jquery验证表单。一切正常,除非我无法翻译该表单的错误消息。我尝试使用{%trans%}并将消息作为已使用ugettext翻译的上下文变量进行发送,但均无用。肯定有一种方法可以做到这一点。任何帮助都会很棒,谢谢!
代码:
var formValid = {mail_num_valid: false, name_valid: false};
function checkValidation() {
if (formValid.mail_num_valid == true && formValid.name_valid == true) {
$('#submitButton').removeAttr("disabled");
} else {
$('#submitButton').attr("disabled", "true");
}
};
$('#{{ form.mail_or_num.id_for_label }}').on('input', function() {
var mail_num = $(this).val();
function msg(content) {
$('#mail_num_error').text(content).show();
};
function hide() {
$('#mail_num_error').hide();
};
var num_exp = new RegExp('^[0-9]+$');
var mail_exp = /\S+@\S+\.\S+/
num_test = num_exp.test(mail_num);
mail_test = mail_exp.test(mail_num);
if (mail_test) {
formValid.mail_num_valid = true;
hide();
}
else if(mail_num.length == 0) {
formValid.mail_num_valid = false;
hide();
}
else if (num_test && 9 <= mail_num.length && mail_num.length <= 13) {
formValid.mail_num_valid = true;
hide();
}
else if (mail_num.length < 5) {
msg({% trans 'Too short to be a valid mail or number' %}); // This sends an error.
formValid.mail_num_valid = false;
}
else if (num_test && mail_num.length < 9) {
msg("The number is too short");
formValid.mail_num_valid = false;
}
else if (num_test && mail_num.length > 13) {
msg("The number is too large");
formValid.mail_num_valid = false;
}
else {
msg("Mail not correct");
formValid.mail_num_valid = false;
}
checkValidation();
});
$('#{{ form.name.id_for_label }}').on('input', function() {
var name = $(this).val();
function msg(content) {
$('#name_error').text(content).show();
};
function hide() {
$('#name_error').hide();
};
if (name.length > 2) {
formValid.name_valid = true;
hide();
}
else if (name.length == 0) {
formValid.name_valid = false;
hide();
}
else {
msg("The name is required");
formValid.name_valid = false;
}
checkValidation();
});
<form method="post">{% csrf_token %}
<div class="fieldWrapper">
<label for="{{ form.mail_or_num.id_for_label }}">Mail/Number:</label>
{{ form.mail_or_num }}
<p id="mail_num_error"></p>
</div>
<div class="fieldWrapper">
<label for="{{ form.name.id_for_label }}">CC yourself?</label>
{{ form.name }}
<p id="name_error"></p>
</div>
<div class="fieldWrapper">
<label for="{{ form.message.id_for_label }}">Your message:</label>
{{ form.message }}
</div>
<input type="submit" id="submitButton" value="Send message" disabled />
</form>