jQuery with remote validation does not wait for answer from server - javascript

I've noticed, that sometimes my validation code works wrong:
var $validator = $("#checkoutForm").validate();
...
if (!$validator.element($sameShippingAddress)) {
...
}
Debugging with Firebug showed, that sometimes $validator.element($sameShippingAddress) would return undefined (I guess it just does not wait till response is returned) and that would be assumed as false, even if element is valid.
If add code like this before if statement, everything works fine:
while (validator.element($sameShippingAddress) !== undefined) {
}
Question is if that is right solution and there's no better way to handle problem with validation plugin itself?
Update: I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Infinite while loop on validator variable is not a good choice. Instead use the code below that utilise Javascript timer. You can show animated processing/server response graphics after validate() method.
var validator = $('#resetpassword').validate({///your code...})
doTimer();
function timedCount()
{
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (validator === undefined)
{
timedCount();
}
}
if(validator==true)
$('#form').ajaxSubmit(options);

It's hard to tell how you are handling successful submissions or if you uses the css class to denoted required fields, but the following is how it's done in the demo for the plugin:
$.validator.setDefaults({
// code to be executed on submit
submitHandler: function() { alert("submitted, replace this with your server request");}
});
$().ready(function() {
// validate the comment form when it is submitted
// use css class .required for fields you want the validator to check
// if your form is valid then it is handled by the submitHandler
// if not the plugin displays error messages
$("#checkoutForm").validate();
//validate can take a block for custom validation and error messages
});
Hope this helps you find a solution and isn't just more of the same (also just realized this question is a year old, but I already wrote this so...)

Obiously, it is not the best solution. Instead add
if (!$validator.element($sameShippingAddress)) {
...
}
in the Ajax callback function.

Related

How do I show what validation errors Parsley.js has found?

I'm using Parsley.js to validate part of a form like in this example. However, the validate() method always returns false, even when that piece of form should validate.
No error messages are displaying, and I want to see what it is that's failed validation.
I can't see a way to get Parsley to simply return all the errors found, so I can see them in the console. Have I missed something obvious?
You can use something like this:
window.Parsley.on('field:error', function() {
// This global callback will be called for any field that fails validation.
console.log('Validation failed for: ', this.$element);
});
from http://parsleyjs.org/doc/index.html#events
There are probably (hopefully) better ways to do this, but this kind of thing is what I ended up using to get some insight into what's being validated and what is/isn't passing:
function validateAnswers(groupName) {
var formInstance = $('.my-form').parsley();
var isValid = formInstance.validate(groupName);
// Just for debugging:
$.each(formInstance.fields, function(idx, field) {
if (typeof field.validationResult === 'boolean') {
// Validated.
console.log('Passed: ' + field.value);
} else if (field.validationResult.length > 0) {
console.log('Failed: ' + field.validationResult[0].assert.name);
}
});
return isValid;
}
This worked on my very simple form with 'required' radio buttons; no idea how it would work on larger forms with different types of fields and validation requirements.
Any better answers or improvements?
Here's what I did for this type of situation.
var formElements = $('form .elementClass').parsley(); // Get all elements inside your form
// Loop through all the elements found
_.forEach(formElements, function(formElement) { //You can use a regular for loop if you prefer
var errors = ParsleyUI.getErrorsMessages(formElement); //Get the list of errors for this element
if (errors.length) {
// Output the first error in the array. You could loop this too.
console.log(errors[0]);
}
});
It feels a bit ugly, but it gets you what you need.

Jquery form validation - How not to execute code before validating

I have written a small form with some calculations. Now the calculation are done using button click event.
$('a#check_var').click(function() {
// the below call the form validation
$("#bet_cal_form").valid();
<- My code here ->
});
Now everything works, problems is I don't want my code to execute unless there are no error in the form validation. Currently I get the error messages but also my code get executed.
Use an if statement, of course.
if ($("#bet_cal_form").valid()) {
// Stuff that should only be done if form is valid
}
You need an if and to cancel the link and since all IDs need to be unique, you do not need the a in the selector
$(function() {
$("#check_var").on("click",function(e) {
e.preventDefault();
// the below call the form validation
if($("#bet_cal_form").valid()) {
<- My code here ->
}
});
});

ASP.NET Form validation - success event in JavaScript?

I would like to subscribe to whatever event is fired when my ASP.NET form is validated successfully.
Here is the scenario: On the click of a button on a payment form, I want to show a message 'processing,' however I only want to show this button when the for is validated succesfully.
I am using native ASP.NET form validation.
In a round-about way, you can if you override the Page_ClientValidate method as in:
var fn = Page_ClientValidate;
Page_ClientValidate = function(..) {
var result = fn(..);
if (result == true) {
//run code for success
}
}
I don't know why this was demoted but this approach is great because it works from all validation scenarios for customization (from buttons, WebForms_DoPostBackWithOptions client method, etc.).
HTH.
I don't think that the built in validators expose any such events. You could always use the CustomValidator and provide a OnClientValidate method that will combine the validation you're looking for as well as the UI changes you desire.
Call the following Javascript function whenever you want and pass the validation group name of your form to it..
function ValidateForm(ValidationGroupName)
{
var validated=Page_ClientValidate(ValidationGroupName);
if(validated)
{
//do the logic here
return true;
}
else
{
return false;
}
}
Hope this will help you....
I don't think it's going to be easy to do it your way but what you can do is the following:
<asp:Button onclientclick="if (Page_IsValid) return true; else {alert('Not Valid'); return false;}"/>
This will basically throw an error is validation is incorrect, otherwise it will continue.

jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...

asp.net validation with validation group calling Page_ClientValidate not working as expected

Hi I am calling the following javascript when user clicks complete button which is to call validation on all of the validation groups which i have 3.
but what is happening is that only the validation summary for the Photos one is being displayed when the others should also be showing. Can anyone help?
function EnsureValidation() {
Page_ClientValidate('PropertyInformation');
Page_ClientValidate('MarketCondition');
Page_ClientValidate('Photos');
}
See Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously?
Edit
Can't you just call Page_ClientValidate() (without any arguments) to validate all controls on the page?
I know this is an old post, The issue with using only Page_ClientValidate() is that, if you want to validate one group at a time, it won't work as it fires all the validation groups, you can do something like this,
function something(){
if(Page_ClientValidate('Save'))
{
//Your Code
}
else if (Page_ClientValidate('Group2'))
{
//your code
}
else
{
//your code
}
};

Categories