问题
I'm using the jQuery validation plugin, and it works great.
I want to be able to both display a message and trigger a modal (alert() in the example) whenever the remote ajax fails. I can't figure out how to do both. Now, it triggers the alert() as expected, but also appends the error message "Please fix this field", which should be my own custom error message.
Here's what I've got:
$("#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());
}
});
回答1:
Quote OP comment: "The returned string works everytime, but the
.reveal()only fires the first time, after the page is loaded."
I think you're only getting the modal one time because the Validate plugin only constructs the message one time (then uses hide/show). If you want it fired off every time, try the highlight callback function instead. Use in conjunction with onkeyup and onfocusout set to false.
onkeyup: false,
onfocusout: false,
highlight: function(element, errorClass) {
if ($(element).attr('name') === 'remotefieldname') {
$('#myModal').reveal();
}
}
Demo: http://jsfiddle.net/NFRvT/1/
回答2:
I never knew that a message could be a function, normally a message is a string. However, as you have demonstrated, a message can be a function. The reason that you are not getting a message displayed is that if a message is a function, it must return a string.
rules : {...}
messages:
{
tlf:
{
required: "Field tlf is required!",
remote: function (val)
{
alert("failed - " + val + " is already taken!");
return "remote validation failed";
}
}
}
回答3:
Here is how I got it working:
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;
});
And in the rules:
tlf: {
required: true,
digits: true,
minlength: 8,
avail: true
}
And the messages:
tlf: {
required: 'Must enter phone number',
avail: 'Phone number is already taken!'
},
To anyone with similar problems, I found quite alot of help here: https://stackoverflow.com/a/2628442/839716
来源:https://stackoverflow.com/questions/14773262/open-modal-when-jquery-validation-remote-fails