jQuery Validation Plugin – 刷新validation码仅工作一次

我正在使用带有jQuery Validation Plugin的自定义validation码

我的配置如下所示:

$('#contactform').validate({ onkeyup: function(element, event) { $(element).valid(); }, errorElement: 'span', rules: { contactform_captcha: { minlength: 6, maxlength: 6, required: true, remote: /path/to/captcha-check.php }, }, messages: { contactform_captcha: { required: "No code, no email", minlength: function () { return [ 'Enter at least ' + (6 - parseInt($('#contactform_captcha').val().length)) + ' more character(s) to go.']; }, remote: function () { $("#captchaimage").attr("src", /path/to/new/captcha.php+"?r=" + Math.random()); return ['Wrong code, therefore try again']; } }, }, success: function(label) { label.addClass("valid").text("Well done!") }, submitHandler: function(form) { //submit form } }); $('span[class^="error"]:not(.valid)').remove(); 

这段代码的作用是validation是否有6个字符,然后将这6个字符发送到captcha-check.php 。 如果一切正常, captcha-check.php将返回true ,否则它将返回false ,然后调用此函数:

 remote: function () { $("#captchaimage").attr("src", /path/to/new/captcha.php+"?r=" + Math.random()); return ['Wrong code, therefore try again']; } 

如果为false ,则消息函数将更新图像#captchaimagesrc 。 一切正常,但只是第一次。 我想远程响应消息是缓存的。

此外,如果我在远程远程响应消息中输出Math.random() ,它将不会更新,也许可能有问题。

你的代码:

 messages: { contactform_captcha: { .... remote: function () { $("#captchaimage").attr("src", /path/to/new/captcha.php+"?r=" + Math.random()); return ['Wrong code, therefore try again']; } } } 

我建议您将Math.random()函数转换为PHP并转换为服务器端脚本,而不是在JavaScript中使用+"?r=" + Math.random() ,这是不安全的。 毕竟,没有什么能阻止某人超越Math.random()并发送他们想要的任何数字。

由于messages选项仅用于生成自定义消息,因此您应该在remote方法success响应时触发新的validation码图像。

更像这样的东西……

 rules: { contactform_captcha: { // minlength: 6, // <-- handle this in your PHP for remote // maxlength: 6, // <-- handle this in your PHP for remote // rangelength: [6,6], // <-- same as two rules above required: true, remote: { url: '/path/to/captcha-check.php', success: function (response) { if (response != true) { // trigger a new captcha code from here $("#captchaimage").attr("src", "/path/to/new/captcha.php") } } } } }, 

根据remote方法的文档 :

[server]响应被评估为JSON,对于有效元素必须为true ,并且对于无效元素,可以是任何falseundefinednull ,使用默认消息; 或者一个字符串 ,例如。 “该名称已被采用,请尝试使用peter123”以显示为错误消息。

您还可以利用此function在服务器端生成自定义消息。 事实上,由于你需要在这个字段上调用remote ,所以你的contactform_captcha字段的所有validation规则( minlengthmaxlength等)都可以在服务器端完成。 无论从服务器返回什么字符串都将自动成为错误消息。

一个重要的说明:

我将禁用contactform_captcha字段的onkeyupvalidation,否则,您将在每次击键时调用remote方法,从而在用户完成输入完整validation码之前检查validation码。 这将是一个主要问题,因为用户无法匹配每次击键时更改的validation码。

 onkeyup: function(element, event) { if ($(element).attr('name') != 'contactform_captcha') { $(element).valid(); } }, 
Interesting Posts