gpt4 book ai didi

javascript - jquery .validate() 变量错误消息

转载 作者:行者123 更新时间:2023-12-02 18:25:50 24 4
gpt4 key购买 nike

我在此网站上使用多种语言,并且希望以不同语言显示错误。我想知道是否可以在自定义错误消息中使用变量。

这是 JavaScript 代码片段:

$('form').validate({
$.ajax({
url: 'notification.php',
dataType: 'json',
success: function(data) {
return notification = data;
}
});
rules: {
qty: {
required: true,
digits: true
}
},
messages: {
qty: {
required: notification['qty_error'],
digits: notification['qty_error2']
}
},
invalidHandler: function () {
alert(notification['error2']);
},
submitHandler: function(form) {
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function() {
$.ajax({
url: 'notification.php',
dataType:'json',
success: function(data) {
$('#notification .container').html('<div class="success" style="display: none;">'+ data.confirm1 + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('#notification .success').fadeIn('slow');
}
});

}
});
}
});

如果没有,还有什么其他方法可以做到这一点。

最佳答案

您不能像在这里所做的那样将 .ajax() 放在 .validate() 内部...

$('form').validate({
$.ajax({ ... }); // <-- remove this
...
});

仅指定规则、选项和回调函数 the jQuery Validate plugin documentation可以进入 .validate() 内部。

我发现您已经在 submitHandler 回调函数中包含了相同的 .ajax() 代码。这是完全正确的,因此只需删除上面所示的 .ajax() 即可。

$('form').validate({
// rules, options & callback functions
...
submitHandler: function(form) {
$.ajax({ ... }); // <-- ajax always belongs here
return false;
}
});
<小时/>

就您原来的问题而言,是的,您可以使用变量代替消息。

$(document).ready(function() {

var message_1 = "my custom message 1";

$('#myform').validate({
rules: {
field1: {
required: true
}
},
messages: {
field1: {
required: message_1
}
}
});

});

演示:http://jsfiddle.net/PWdke/

要动态更改消息(插件初始化后)需要 the .rules('add') method .

$(document).ready(function() {

var message_1 = "my custom message 1",
message_3 = "my custom message 3";

$('#myform').validate({
rules: {
field1: {
required: true
}
},
messages: {
field1: {
required: message_1
}
}
});

// programatically over-ride initialized rules/messages below

$('input[name="field1"]').rules('add', {
required: true,
messages: {
required: message_3
}
});

});

演示:http://jsfiddle.net/PWdke/1/

关于javascript - jquery .validate() 变量错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com