I am using the pub / sub jQuery plugin by Peter Higgins. I have run into a problem with JavaScript validation.
This is the crux of the problem…
$.subscribe('/make', function(form_id, fields, path, type) {
for (var i=0; i < fields.length; i++) {
$.publish('/validation/field', [ path+'check_field', $('*[name="'+fields[i]+'"]'), fields ]);
}
if ($('#'+form_id+' .error').length > 0) {
alert('There are errors, please fix the errors before continuing.');
return;
}
The /validation/field will append errors to form fields. When you run this the first time the errors appear but everything is running so quickly an ajax request is sent to save the form. When the form is run the second time the function is stopped correctly as the error classes have been counted.
Is there a way around this?
If the validation is asynchronous
…the usual way you deal with this is to use a callback. In this case, you’d be looking for a callback defined by the validation that tells you when the validation has finished, at which point you could use your code for counting the resulting errors.
If the validation is synchronous
The above assumes that the validation involves an asynchronous activity of some kind. It doesn’t look like that pub/sub plugin provides any asynchronicity, so this would be down to what your subscriber for
/validation/fielddoes. If it does an ajax call or asetTimeoutor similar, then you’ll need a callback.If the
/validation/fieldsubscriber does the validation synchronously, then I’m surprised you’re having a problem with the fields not being counted correctly afterward. But if you are, you can probably solve it by giving the browser just a moment to breathe:The
0parameter tosetTimeoutmeans “call me back in zero milliseconds”, but no browser will actually do that — it’ll typically be 4-10 milliseconds later. The point is that it will be asynchronous, after the browser has had a chance to catch up and re-invoke the JavaScript layer.Be careful though, make sure that the thing doing the validating is doing it synchronously. If it isn’t, if it’s doing anything async, then the above introduces a race condition into your code where sometimes it will seem to work, other times it won’t work. Race conditions will bite you, so double-check. 🙂