I have a single form and 3 input type submit buttons: back, send, search. The "back" should not validate the form and take me back, the "send" should validate only the email field, the "search" should validate first name, last name and postcode. I have been working on this but to me the update/assign rules part seems a bit verbose. Maybe there's a way to do it better. I have a working jsfiddle: http://jsfiddle.net/1u7tb48L/ And this is my javascript:
$("#formValConfirmIdEmail").validate({
debug: true,
rules: {
emailLogin: {
required: true
},
firstName: {
required: true
},
lastName: {
required: true
},
postCode: {
required: true
}
},
messages: {
emailLogin: {
required: 'Required'
},
firstName: {
required: 'Required'
},
lastName: {
required: 'Required'
},
postCode: {
required: 'Required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element);
}
});
// Update rules for send button
$('#formValConfirmIdEmail #sendBtn').on('click', function () {
$('#emailLogin').rules('add', {
required: true
});
$('#firstName').rules('remove');
$('#lastName').rules('remove');
$('#postCode').rules('remove');
$('#firstName, #lastName, #postCode').closest('.control-group').removeClass('error');
$('#formValConfirmIdEmail').valid();
});
// Update rules for search button
$('#formValConfirmIdEmail #searchBtn').on('click', function () {
$('#firstName').rules('add', {
required: true
});
$('#lastName').rules('add', {
required: true
});
$('#postCode').rules('add', {
required: true
});
$('#emailLogin').rules('remove');
$('#emailLogin').closest('.control-group').removeClass('error');
$('#formValConfirmIdEmail').valid();
});
Thanks for your help!
Use the .rules()
methods and when the selector contains multiple elements, wrap it inside of a jQuery .each()
.
$('#formValConfirmIdEmail #sendBtn').on('click', function () {
$('#emailLogin').rules('add', 'required');
$('#firstName, #lastName, #postCode').each(function () {
$(this).rules('remove');
});
$('#firstName, #lastName, #postCode').closest('.control-group').removeClass('error');
$('#formValConfirmIdEmail').valid();
});
Since it's just a simply boolean rule, declare it using class="required"
and add/remove the class
instead of using the .rules()
method.
$('#formValConfirmIdEmail #sendBtn').on('click', function () {
$('#emailLogin').addClass('required');
$('#firstName, #lastName, #postCode').removeClass('required').closest('.control-group').removeClass('error');
$('#formValConfirmIdEmail').valid();
});
NOTE: Your errorPlacement
function is a bit superfluous as error.insertAfter(element)
is already the default. Remove it entirely and the behavior is exactly the same.