1

So here's my problem.

I'm currently working on a PhoneGap application using jQuery Mobile and the Validation jQuery plugin for form validation.

I'm trying to set up a custom rule so that it will check to see if a name is already in the database, and if so, prevent the form from being submitted until the user chooses a name that is unique.

The problem is one that I've encountered before but have not yet managed to properly solve. When I call the method that executes the SQL select statement, the success callback does not get completed until after the validator has already completed and thrown false. This means that if a user enters a unique name, it will display an error, but if the user forces it to re-validate the fields, it will then be valid because the success callback had, in the meantime, completed.

Here's the relevant code:

var nameUnique;

jQuery.validator.addMethod("nameIsUnique", function(value, element) {
        checkNameSQL();
        return this.optional(element) || nameUnique;
    }, "This name is already in use. Please choose another.");

$('#createForm').validate({
    rules: {
      createName: {
        required: true,
        nameIsUnique: true
      },
      createDescription: {
        required: true
      }
    },
    //snip//
});

function checkNameSQL()
{
var name =   document.forms['createForm'].elements['createName'].value;
if (!(name == null || name == ""))
{
    dbShell.transaction(function(tx) {
       tx.executeSql("SELECT STATEMENT",[name],function(tx,results){if(results.rows.length==0){nameUnique = true;}},errorHandler)
    },errorHandler);
}
}

I've simplified it where it makes sense, cutting out code not relevant to the question. As you can see, I call the method to check if the name exists, but before the success callback function triggers to set nameUnique to true, it's being returned by the validator, causing a false error.

How should I change my code to prevent this from occurring? What general programming practices should I follow to circumvent similar problems in the future? Thanks!

5
  • Shouldn't your checkNameSQL function be returning something to the addMethod() method? Otherwise how does the latter know the result of the SQL query? In any case, since the SQL query is an asynchronous event, returning a value is going to be difficult. This is a question of sychronicity. Have a look into jQuery's deferred objects - that would be the easiest resolution to this.
    – Mitya
    Jun 30, 2012 at 22:01
  • Currently, the success callback for 'executeSQL' checks the results to see if it is empty (if it is, then there were no matches), and sets the variable to be checked by the validator to true. Putting 'return true' in its place does nothing, so far as I can tell. I'll take a look at deferred objects though, thanks. Jun 30, 2012 at 23:02
  • I just posted some resources on this in an answer to another question - see stackoverflow.com/questions/11278018/…
    – Mitya
    Jun 30, 2012 at 23:09
  • Thanks. I've taken a look at those, but it's not helping so far. The first problem is that deferred objects seem to be most useful for ajax, but this isn't actually ajax, so it seems forced. But even so, using it in a fashion similar to what you linked (using it in a non-ajax fashion), I still can't get it to work correctly. I create a deferred object in checkNameSQL(), resolve it with .resolve(true) or .resolve(false), and return a promise. I then, inside addMethod, use $.when(checkNameSQL()).done(function(status){nameUnique=status;}); but it still finishes late. Totally stuck. Jul 1, 2012 at 5:45
  • did you check my solution in answer??
    – dhaval
    Jul 4, 2012 at 17:48

1 Answer 1

1

You can return pending as a value from the addMethod() besides true and false which can be used to delay the validation. For more info you can check the source of validation library.

Try this way:

$.validator.addMethod("nameIsUnique", function(value, element) {
    var validator = this;
    var previous = this.previousValue(element);
    checkNameSQL(value, function(status) {
        var valid = status === true;
        if (valid) {
            var submitted = validator.formSubmitted;
            validator.prepareElement(element);
            validator.formSubmitted = submitted;
            validator.successList.push(element);
            validator.showErrors();
        } else {
            var errors = {};
            var message = status || validator.defaultMessage(element, "remote");
            errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
            validator.showErrors(errors);
        }
        previous.valid = valid;
        validator.stopRequest(element, valid);
    });
    return "pending";
}, "This name is already in use. Please choose another.");

function checkNameSQL(name, callback) {
    if (!(name == null || name == "")) {
        dbShell.transaction(function(tx) {
            tx.executeSql("SELECT STATEMENT", [name], function(tx, results) {
                if (results.rows.length == 0) {
                    nameUnique = true;
                    callback(true);
                }else{
                    callback(false);
                }
            }, errorHandler)
        }, errorHandler);
    }
}

For demo check this fiddle - http://jsfiddle.net/dhavaln/GqsVt/

4
  • Just did some quick testing and it's working. Brilliant! Thanks for the help. But I'd be remiss if I didn't ask if you could explain it a bit, as there's no point in using code I can't completely follow. There's some syntax I'm not fully familiar with. Namely, these 3 lines: var valid = status === true; var message = status || validator.defaultMessage(element, "remote"); errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; Could you explain what these lines are saying? I've seen some of the syntax before, but I don't know it yet. Thanks again! Jul 5, 2012 at 20:25
  • var valid = status === true;, assigns the value of status to valid only if status is a boolean variable or status is undefined
    – dhaval
    Jul 6, 2012 at 5:46
  • var message = status || validator.defaultMessage(element, "remote");, captures the message developer has set for validation failure or for remote status. In the source, messages map there is a field remote also.
    – dhaval
    Jul 6, 2012 at 5:51
  • errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;, sets the remote error in the error map so that ui can be updated. message can be either a direct string or a function returning a string. Once error is set the validator.showErrors(errors); is called to use that delayed set error to re-display updates on screen
    – dhaval
    Jul 6, 2012 at 5:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.