Server side validation using JQuery validator (Cakephp)
Hi i am currently doing a school project using cakePHP. I have the following form and assume that the form tag is created.
<?php echo $form->input('number',array('id'=>"number",'title'=>"Please enter a number with at least 3 and max 15 characters ha!"));?>
<?php echo $form->input('secret',array('id'=>"secret"));?>
<?php echo $form->input('math',array('id'=>"math",'title'=>"Please enter the correct result!"));?>
<?php echo $form->input('userName',array('id'=>"userName",'title'=>"User Exist"));?>
I am using a client side validation and here is the code that:
$.validator.addMethod("buga", function(value) {
return value == "buga";
}, 'Please enter "buga"!');
// this one requires the value to be the same as the first parameter
$.validator.methods.equal = function(value, element, param) {
return value == param;
};
$().ready(function() {
var validator开发者_运维问答 = $("#texttests").bind("invalid-form.validate", function() {
$("#summary").html("Your form contains " + validator.numberOfInvalids() + " errors, see details below.");
}).validate({
debug: true,
errorElement: "em",
errorContainer: $("#warning, #summary"),
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
success: function(label) {
label.text("ok!").addClass("success");
},
rules: {
"data[User][number]": {
required:true,
minlength:3,
maxlength:15,
number:true
},
"data[User][secret]": "buga",
"data[User][math]": {
equal: 11
}
},
submitHandler: function(form) {
form.submit();
}
});
});
The above only does client side validation can do for the first three inputs but my last input for this case may require to check the username is unique. How am i able to do the ajax call to the server? I am just confused in that part. Hope someone can guide me.
jQuery validate has a specific rule for server side validation (remote)
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
The page above contains all of the information you need to make the request, the second example is pretty much your use case.
The remote script should return only text, either true or false.
See this page:
http://jquery.bassistance.de/validate/demo/milk/
open up your firebug/chrome console and look at the request after you fill in an email address and click submit.
Good luck with your project.
精彩评论