JQuery Validate Plugin - RegEx email prefix, domaiin suffix, and duplicate check - in one go!
I'm using the wonderful Validation plugin for JQuery, and so far, so good - I even have it passing the entered email address to check against a d开发者_如何学Goatabase to make sure duplicate emails can't be entered. To extend this, however, I want to also ensure that the email prefix (before the @ symbol) does contain at least one period (.) - this is to ensure the users are using their firstname.lastname email address, and not their firstletterlastname email address (and to prevent them from having two accounts using each format).
As stated before, the remote validation of the address itself works fine, but the problem is the response only comes back as a JSON true/false value - if I could validate it in my server-side script, then pass back a string value, there might be some way of displaying an error message for the field appropriate to the error(s) - e.g.: "your email must be firstname.lastname", "the email suffix must be company.com", and "that email address is already registered". I've been reading the JQuery docs on Validation, but nothing I've found allows me to pass back more than just true or false.
I've ended up solving this thanks to Andrew's help, as well as this post: jQuery remote validation with server generated error message The key was ensuring that the strings were encapsulated in double quotes, whereas the true string being passed back wasn't, so it would evaluate correctly and not display an error message. Yay for JQuery and the awesome Validation plugin!
Any ideas/pointers on how to implement this would be greatly appreciated, and considering I looked through all 700+ entries on JQuery Validation here at SO, perhaps it will benefit others as well. Thanks in advance!
Here's some code with what I'm doing:
$("#MemberInfo").validate({
errorPlacement: function(error, element) {
error.insertAfter(element);
},
rules: {
Memberemail: {
required: true,
//minlength: 1,
email: true,
remote: {
url: "checkReg.cfm",
dataType: "json"
}
},
},
messages: {
Memberemail: {
required: "Please enter a valid @company.com email address",
minlength: "Please enter a vaild email address",
remote: jQuery.format("{0} is already registered")
}
}
});
Check out the documentation for the remote
option:
The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.
So in your server-side code, if you return a string, it should be shown as the error message.
精彩评论