Automatically close qtip2 using JQuery .validate() - javascript

I'm working on a form which implements QTip2 to display a tooltip once someone tries to submit a form where data is missing. Everything works as intended, however I would like the tooltip to be removed once the error class is removed (effectively once someone types in the input field). I have the following code for my validation currently:
$('#form0').validate({
rules: {
Name: "required",
Email: {
required: true,
email: true
},
Subject: "required",
Message: "required"
},
errorPlacement: function (error, element) {
$('#Name').qtip({
content: 'Please enter your name',
position: {
target: 'mouse', // Track the mouse as the positioning target
adjust: { x: 5, y: 5 } // Offset it slightly from under the mouse
},
style: { classes: 'qtip-red' }
});
return true;
},
errorClass: "form-error"
});
As you can see, once someone tries to submit the form the class "form-error" is assigned to the input field, so I would like the tooltip to be removed as well once this class is removed. I tried the following, but it did not work, not sure why:
onHide: function() { $(this).qtip('destroy'); }

I found a solution to this problem by adding the following code inside errorPlacement {}:
events: { show: function (event, api) { if (!element.hasClass('form-error')) event.preventDefault(); } },
show: {
delay: 0,
target: element
},
hide: { target: element },

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?

Multiple instances of jQuery Validation Plugin on a JSP page

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.

jQuery .validate rules don't appear to be applying? (jsfiddle)

http://jsfiddle.net/sK9tL/1/
When I manually add the rule()'s in the console on my form page, it appears to validate as expected.
I'm not sure if there is something wrong with the way I am formatting this?
$('#freeFormAdd').validate({
rules:{
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
}
});
Then I use the .valid() to determine if the form is ready to submit. Since the page is "seamless" I don't need the form to submit, just to add some items to a cart (which is commented out in the jsfiddle).
Any advice?
Your form elements should have name attribute not id attribute, validator selects the elements based on their name attributes. Also instead of listening to the click event, you can use the submitHandler method:
$('#freeFormAdd').validate({
rules: {
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
},
submitHandler: function () {
alert('the form is valid');
}
});
Please note that I have moved the button to the form element's context so it triggers the submit event.
http://jsfiddle.net/QU3XM/

Submit button disabled after first click

After clicking the "Contribute" button on my site, an overlay form will appear; however, if someone were to immediately click "Send Pledge" before supplying the info, the button is disabled (as is the Stripe button) for further use. As a result, they can't add a credit card or submit the form; it is permanently disabled until they refresh the page.
How can I change it so that the "Send Pledge" button is still active even after the first click? Please let me know if more information is needed.
A live demo can be found here: http://www.cantedpictures.com/9test/
Otherwise: here is the js:
$(function(){
$("#donateModal").on('show', function() {
// Fix StripeButton sizing bug on Firefox and IE
$(".stripe-button-inner, .stripe-button-inner iframe").width(132).height(36);
// ensure button scrolls with the rest of the page
$(".stripe-button-inner iframe").css('position', 'relative');
});
// Stripe Button Triggers formDomElement.submit().
// We intercept it and notify user we have received the token
var paymentForm = $('#payment-form')[0];
paymentForm.original_submit = paymentForm.submit;
paymentForm.submit = function() {
$("#stripe-button-holder .stripe-button-inner").html(
'<span class="label label-success">
<i class="icon-ok"></i> Card Added</span>');
return false;
};
$('#payment-form').validate({
rules: {
'first-name': {
minlength: 1,
required: true
},
'last-name': {
minlength: 1,
required: true
},
email: {
required: true,
email: true
},
amount: {
required: true,
min: 10,
},
'tos-agreed': {
required: true
}
},
messages: {
'tos-agreed': 'You need to agree to the Terms of Service',
'first-name': 'Please give us your first name',
'last-name' : 'Please give us your last name',
'email' : 'Please give us your email so that we can contact you',
'amount' : 'Please pledge at least $10.'
},
errorPlacement: function (error, input) {
$(input).closest('.controls').append(error);
},
highlight: function(el) {
$(el).closest('.control-group').addClass('error');
},
unhighlight: function(el) {
$(el).closest('.control-group').removeClass('error');
},
submitHandler: function(form) {
// ensure CC info has been entered
if (! $('[name=stripeToken]').val()) {
$("#stripe-button-holder").closest('.control-group').addClass('error');
$("#stripe-button-holder").append('<label class="error">
Please Add Payment Information</span>')
window.location.reload();
} else {
form.original_submit();
}
}
});
});//]]>
You should identify your button and replace the below 'button' with '#myButtonId', but once you do you can use
$('button').prop('disabled', '');
to remove disabled property.

errorClass in jquery validate plugin?

I am using jquery validate plugin in my web application to validate forms for blank and other simple validations.
I am using below code to setup jquery validate plugin for my form, there is a erroClass option in it, where I have defined a CSS class name authError which I want to apply on error messages, but its applying the same class to INPUT box as well, I don't want to apply it in INPUT box, just want it for error message. Please check and help. Thanks!
$("#frmSignin").validate({
debug: false,
errorClass: "authError",
errorElement: "span",
rules: {
username: {
required: true,
minlength: 10
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username"
},
password: {
required: "Please enter your password"
}
}
});
Thanks, for the tricks guys, but I instead found a better way by using the jQuery code only. There is a highlight event in validate plugin which is called when error occurred to highlight the error fields, I just removed the class form element when this event is called.
$("#frmSignin").validate({
debug: false,
errorClass: "authError",
errorElement: "span",
rules: {
username: {
required: true,
minlength: 10
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username"
},
password: {
required: "Please enter your password"
}
},
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
}
});
You should actually be just defining different classes for input and span (span since errorElement is set to span, otherwise it will be label), rather than removing the applied class
e.g.
span.authError {color:red;}
input.authError {border:1px dotted red;}
and not just .authError{} which will get applied to both input and span
$("#borrowerForm").validate({
errorElement: 'span',
errorElementClass: 'input-validation-error',
errorClass: 'field-validation-error',
errorPlacement: function(error, element) {},
highlight: function(element, errorClass, validClass) {
$(element).addClass(this.settings.errorElementClass).removeClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(this.settings.errorElementClass).removeClass(errorClass);
},
onkeyup: false,
errorPlacement: function (error, element) { error.insertAfter(element); }
});
In the jQuery validation plugin, the errorClass is both applied to the error message element (usually a <label>, but a <span> in your case) and to the validated element itself. Since you only want to style the error message element, you should write:
span.authError {
// Your error element style.
}
If you want to give css for the error message.
Then in place of using errorClass define css rule
label.error
Check this:
jQuery.validator.messages.required = "";
$('#frm-contact').validate({
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted below'
: 'You missed ' + errors + ' fields. They have been highlighted below';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
onkeyup: false,
submitHandler: function () {
$("div.error").hide();
alert("submit! use link below to go to the other step");
},
highlight: function (element, required) {
$(element).fadeOut(function () {
$(element).fadeIn();
$(element).css('border', '2px solid #FDADAF');
});
},
unhighlight: function (element, errorClass, validClass) {
$(element).css('border', '1px solid #CCC');
}
});

Categories

Resources