问题
I am using jquery validation for my register form, it works perfectly but I'm running into a problem. I check if the email exists, if an email does exists I'm receiving an error message. Now I would like to edit this, so, if the email is free to use. The error message will change to: This email is free to use.
$(document).ready(function(){
$("#registratieform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "includes/check_email.php",
type: "post",
complete: function(data){
if( data.responseText == "false" ) {
alert("Free");
}
}
},
},
},
messages: {
email: {
required: "This field is required",
email: "Please enter a valid email address",
remote: jQuery.format("{0} is already taken")
},
},
});
});
The Alert works, but this message has to appear in the label where the errors are. Is this possible?
回答1:
You can use success
option.
If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like “ok!”.
The example in the doc: Add a class “valid” to valid elements, styled via CSS, and add the text “Ok!”.
$("#myform").validate({
success: function(label) {
label.addClass("valid").text("Ok!")
},
submitHandler: function() { alert("Submitted!") }
});
In your code:
$(document).ready(function(){
$("#registratieform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "includes/check_email.php",
type: "post",
complete: function(data){
if( data.responseText == "false" ) {
alert("Free");
}
}
},
},
},
messages: {
email: {
required: "This field is required",
email: "Please enter a valid email address",
remote: jQuery.format("{0} is already taken")
},
},
success: function(e) {
// Remove error message
// Add success message
},
});
});
I recommended read this: .validate()
回答2:
@Ruub: The remote message should be a function, and the remote in rule just an url for check Example:
$("#registratieform").validate({
rules: {
email: {
required: true,
email: true,
remote: "includes/check_email.php"
}
},
messages: {
email: {
required: "This field is required",
email: "Please enter a valid email address",
remote: function() { return $.validator.format("{0} is already taken", $("#email").val()) }
},
},
});
In server side (includes/check_email.php):
if (!isValidEmail($_REQUEST['email'])) {
echo "false";
exit;
}
回答3:
I`v found solution for our problem, a spend a day to all existed solution but noone satisfied me and learn a bit source code of jqvalidator I found that it is easy to realize it
$("#myform").validate({
rules: {
somealiasname: {
required: true,
remote: {
url: "www.callthisurl.com/remote",
type: "GET",
success: function (data) {// Here we got an array of elements for example
var result = true,
validator = $("#myform").data("validator"), //here we get the validator for current form. We shure that validator is got because during initialization step the form had stored validator once.
element = $("#myform").find("input[name=somealiasname]"),
currentAlias = element.val(),
previous, errors, message, submitted;
element = element[0];
previous = validator.previousValue(element); // here we get the cached value of element in jqvalidation system
data.forEach(function (it) {//here we check if all alias is uniq for example
result = !result ? false : it.alias != currentAlias;
});
validator.settings.messages[element.name].remote = previous.originalMessage; // this code I found in the source code of validator (line 1339)
if (result) {
submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
errors = {};
message = validator.defaultMessage(element, "remote");
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = result;
validator.stopRequest(element, result);
}.bind(this)
}
}
}
```
tadam - everything is perfectly!
This code has been tested with jqvalidation 1.14.0
I hope, I could help somebody
回答4:
Replace below code with your complete function :
dataFilter: function (data) {
return 'false';// If email not exist
return 'true';// If email exist ( Display message on return true )
}
Please check this it will be help.
回答5:
In case to use Laravel, I find this useful. The key is using dataFilter
email: {
required: true,
remote: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: "existsEmail.php",
data: {email: function() {
return $('#email').val();
}},
dataFilter: function(response) {
var data = JSON.parse(response);
return data.success;
},
}
messages: {
email: {
required: "Email Required",
remote: $.validator.format("Email Invalid"),
}
It's important return with status 200 (or void), even in return false. If you put another status, this doesn't send (nothing) the correctly response to dataFilter
public function existsEmailCloud(Request $request){
$sEmail = strtolower($request->email);
$result = GeneralFunctions::existsEmail($sEmail);
if($result) {
return Response::json([
'success' => true,
], 200);
} else {
return Response::json([
'success' => false,
], 200);
}
来源:https://stackoverflow.com/questions/11342716/jquery-validation-form-remote-rule-success-message