Multiple instances of jQuery Validation Plugin on a JSP page - javascript

SOLVED: $.extend() twice in a row simply overwrites the previous object because objects are passed by reference. My fix was to do this:
var updateUserObj = $.extend({}, validationPluginDefaults);
var newUserObj = $.extend({}, validationPluginDefaults);
Then the validators are executed like this:
var whateverValidator = $.extend(updateUserObj,{new rules})
Update: Further research shows that what I'm trying to do appears to be correct but the problem may be in the object I am extending - "validationPluginDefaults"). Here it is below:
var validationPluginDefaults = {
ignore: [],
errorElement: 'p', //default input error message container <p>
errorClass: 'text-error', // default input error message class
focusInvalid: true, //focus on the first invalid field
messages: {},
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (el) { // hightlight error inputs
//jQuery(el).closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (err, el) {
jQuery(el).next(".text-error").hide();
jQuery(el).next(".text-error").remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onfocusin: function () {},
onfocusout: function () {}
};
From my testing it appears that even though I have two separate forms on a JSP page and each has different validation that I can still only use one jQuery Validate Plugin instance per page; is this correct?
Here's my code:
// Define validation rules for form one
var formOneValidator = $.extend(validationPluginDefaults,{
rules: {
firstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
lastName: {
minlength: 2,
required: true,
},
email: {
required: true,
email: true
}
}
});
var formTwoValidator = $.extend(validationPluginDefaults,{
rules: {
newFirstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
newLastName: {
minlength: 2,
required: true,
},
newEmail: {
required: true,
email: true,
}
}
});
$("#formOne").validate(formOneValidator);
$("#formTwo").validate(formTwoValidator);
What happens here is that formOne validator takes on all the rules of formTwoValidator after this code executes.
Is the solution to have only one validator and swap out rules depending on which form I'm in? It just seems strange that I wouldn't be able to define separate validators for each form on the page. Am I fundamentally misunderstanding something here?

you could use knockout and give each page a different view model which handles the different validation. That is how i would do it but i'm sure there will be a better answer.

Related

validating that a canvas has been drawn in

I'm implementing an online waiver where a client has to sign into canvas before they can complete the form. I use Signature_Pad from szimek and jquery-validate and would like to have the canvas (which is part of the form) be included. I tried a custom formatter, like so:
let wrapper = document.getElementById("signature_pad");
var signaturePad = new SignaturePad(wrapper.querySelector("canvas"), {
backgroundColor: 'white'
});
jQuery.validator.addMethod("checkSignature", function(value, element) {
return signaturePad.isEmpty() == false;
}, "Signature must be provided");
$("form[name='form-waiver']").validate({
rules: {
WaiverName: {
required: true,
minlength: 2
},
signature_pad: {
checkSignature: true
}
},
messages: {
WaiverName: "The name has to be filled out"
},
successClass: "valid",
errorClass: "invalid",
submitHandler: function (form) {
...
}
};
However, the form validates even if the canvas is empty. Is there a method to include the canvas in the form validation?

Assign dynamically loaded html element to variable

I'm trying to validate fields loaded using jQuery $().load();.
with jquery validation plugin (jqueryvalidation.org)
My code is:
var contactForm = $('#contact-form');
contactForm.validate({
rules: {
name: {
required: true,
},
email: {
required: true,
email: true
},
phone: {
required: false,
phoneUS: true
},
message: {
required: true
}
}
});
Unfortunately it doesn't work with elements loaded with load();
After some google searching I found some solution but they all are aimed on "events", not to pass dynamically added input to variable:
$(document).on('click','#submit',function() {});
I also tried to approach it with this code bellow :
$('.home').click(function() {
$("#article").load("./ #article > *",function(){
contactForm = $(this).find("#contact-form");
});
Also doesn't work though :(
I will appreciate any clues and help.
Try to add them dynamically :
$("#contact-form").find('input').each(function () {
$(this).rules("add", {
required: true
});
});
Hope this helps.

How to dynamically add a validation rule using jquery validation plugin

I'm trying to dynamically add a validation rule to some dynamic controls using http://jqueryvalidation.org/ but its not working.
$(".rtxt").each(function () {
$(this).rules('add', {
required: true
});
});
<input class='rtxt' name='txtDocName' id='txtDocName' style='width:220px;' type='text' >
Don't know what i am missing here.
I can't use 'required' attribute as its not supported by IE9 so i will have to use jquery validation plugin.
Here is fiddle
http://jsfiddle.net/ed4fg1xo/
Also, i need to do validation on div click event.
$(document).ready(function () {
// 1. prepare the validation rules and messages.
var rules = {
textbox1: {
required: true,
minlength: 2
},
textbox2: "required",
textbox3: "required"
};
var messages = {
textbox1: {
required: "textbox1 is required",
minlength: "textbox1 needs to be at least length 2"
},
textbox2: "textbox2 is requried",
textbox3: "textbox3 is required"
};
// 2. Initiate the validator
var validator
= new jQueryValidatorWrapper("FormToValidate",
rules, messages);
// 3. Set the click event to do the validation
$("#DivIdName").click(function () {
if (!validator.validate())
return;
alert("Validation Success!");
});
});

Jquery css 'display:block' not work

I am attempting to create a simple validation function for my contact form.
Click here At the moment, once details are submitted the form keeps display:none even when entries are incorrect. I have tried to target the form id Which doesn't seem to be working either.
below is a snippet of my function
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
form.validate();
$(form).submit(function(e) {
if ($('#ajax-contact').valid()) {
$('#ajax-contact').validate({
rules: {
name: {
rangelength: [2, 40],
},
email: {
rangelength: [2, 40],
email: true,
required: true
},
errorClass: "error",
highlight: function (input) {
$(input).closet('.required').removeClass('has-success').addClass('has-error');
}
}
})
} else {
$("#ajax-contact").css({'display:block'});
console.log('not working');
}
})
.css should be used this way:
$("#ajax-contact").css('display','block');
and if you have multiple .css to be set then you can go with
$("#ajax-contact").css({'display':'block','position':'relative'});
Try css({display: "block"}) as it takes an object as options. Not an array

Using jQuery Validation Plugin with dynamic form elements

I have a page that contains multiple forms, and each form can contain any number of elements that have a common root in its name. I'm trying to use this answer to validate a form when it's submitted, but I get a TypeError: a.data(...) is undefined error on jquery.validate.js. My code is below.
var valForm = function(kit_id) {
$('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
$("#frm_" + kit_id).validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
if (! $("#frm_" + kit_id).valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};
The function is called when a link is clicked.
Save
Any suggestions?
I think you have to call .validate() on the form before you can call .rules() on the inputs in that form. You should also call .rules() only on the inputs in the form you're submitting.
var valForm = function(kit_id) {
var form = $("#frm_" + kit_id);
form.validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
form.find('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
if (! form.valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};

Categories

Resources