I have a single form with some div blocks inside it. All the divs have their fields and buttons. On button click i need to validate just THAT div(button's parent) and submit some fields to server asynchronously. Everything works fine, but not the validation. I use JQuery validation plugin. As i see i cant write such code:
<script type="text/javascript">
//.......
// Validator for general information
var userProfileGeneralValidator = $("#form1").validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
txtPrivateNumber: {
required: true
}
},
messages: {
txtPrivateNumber: {
required: "Required!"
}
},
errorPlacement: function (error, element) {
if (error.text() != "") {
}
},
success: function (lbl) {
}
});
// Validator for password information
var userPasswordValidator = $("#form1").validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
txtOldPass: {
required: true,
minlength: 5
}
},
messages: {
txtOldPass: {
required: "Required!"
}
},
errorPlacement: function (error, element) {
if (error.text() != "") {
}
},
success: function (lbl) {
}
});
</script>
And than call userPasswordValidator.form()
on one button click and userProfileGeneralValidator.form()
on other button click. Are there any tricks to achieve my goal: several form parts to validate separately with jquery?
PS: found one solution: put several forms in main form. One per div. But think its dirty.
UPDATE with solution ive used: in the end i've taken the answer from this question, but made the following changes:
i call the validate()
method on whole form somewhere in document.ready. As validate options i add rules for all the controls i need to validate(they are nested in some divs
as groups). Messages/errorPositions/Success i declare in the files, where i works with clicks on the buttons in that divs, where the controls to validate are nested. And to validate just that div i use:
var validator = $("#topUserProfile").validate(userProfileGeneralValidator);
// Validate and save general information
if (!validator.form()) {
return;
}
Where #topUserProfile
is the name of the div that is containing controls; userProfileGeneralValidator
is variable that holds additional options for validation(messages/ position/ etc). Thank you all, who helped.