当jQueryvalidation远程失败时打开模态

我正在使用jQueryvalidation插件,它工作得很好。

我希望能够在远程ajax失败时显示消息并触发模式(示例中为alert())。 我无法弄清楚如何做到这两点。 现在,它按预期触发alert(),但还附加错误消息“Please fix this field”,这应该是我自己的自定义错误消息。

这是我得到的:

$("#adresse-form").validate({ errorElement: "span", rules: { navn: { required: true, minlength: 5, maxlength: 25 }, tlf: { required: true, digits: true, minlength: 8, remote: { url: "/ajax/check_tlf", type: "post" } } }, messages: { navn: "Field Name is required", tlf: { required: "Field tlf is required!", remote: function () { // i want to add the message aswell, not just the alert alert("failed - tlf is already taken!"); } } }, submitHandler: function(form) { doSomethingGreatOnSuccess(); }, errorPlacement: function (error, element) { error.appendTo(element.parent()); } }); 

引用OP评论: “返回的字符串每次都有效,但.reveal()仅在页面加载后第一次触发。”

我认为你只获得模态一次,因为Validate插件只构造一次消息(然后使用hide / show)。 如果您希望每次都关闭它,请尝试使用highlight回调函数。 与onkeyuponfocusout一起使用设置为false

 onkeyup: false, onfocusout: false, highlight: function(element, errorClass) { if ($(element).attr('name') === 'remotefieldname') { $('#myModal').reveal(); } } 

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

我从来不知道消息可能是一个函数,通常消息是一个字符串。 但是,正如您所演示的,消息可以是一个function。 您没有收到消息的原因是, 如果消息是一个函数,它必须返回一个字符串

 rules : {...} messages: { tlf: { required: "Field tlf is required!", remote: function (val) { alert("failed - " + val + " is already taken!"); return "remote validation failed"; } } } 

以下是我如何使用它:

 jQuery.validator.addMethod("avail",function(value,element){ var isSuccess = true; $.ajax({ url: "/avail", type: 'POST', data: { tlf: value }, async: false, success: function (msg) { isSuccess = msg === "true" ? true : false; if (!isSuccess) { $('#myModal').reveal(); } } }); // return isSuccess; }); 

在规则中:

 tlf: { required: true, digits: true, minlength: 8, avail: true } 

和消息:

 tlf: { required: 'Must enter phone number', avail: 'Phone number is already taken!' }, 

对于有类似问题的人,我在这里找到了很多帮助: https : //stackoverflow.com/a/2628442/839716