views:

473

answers:

2

I have a form in which I am using remote validation to check if an email address already exists in the database. However, the catch is that on this form, the user can select between several different "groups", and each group has its own distinct set of email addresses (thus the same email can exist once in each group).

The group selection is a dropdown on the form, and the email address is an input field with remote validation. I have a couple issues. First, I have set up my remote rule like this:

remote: {
    url: 'remote_script.php',
    data: {  group_id:  $('select.group_id').val() }
}

However, this seems to statically set the group_id parameter to whatever the first value in the select is. Meaning, if I change the select, then trigger the remote validation again, the group_id parameter does not change

First, how can I make this parameter dynamic, depending on the value of a select in the form?

Secondly, how do I manually trigger the remote validation on the email address field? When the group_id select is changed, I want to re-trigger the remote validation on the email address field (without changing the value of the field). I tried using

$(selector).validate().element('.email_addr')

But this appears to only trigger the standard validation (required, email), and not the remote call.

A: 

From the second example for remote it looks like functions (evaluated during validation) can be used for data, so

remote: {
    url: 'remote_script.php',
    data: {
        group_id: function () {
            return $('select.group_id').val();
        }
    }
}

should work.

For your second question, did you try passing the validation rules to validate()?

Jeffery To
Yep, you are right, that works for the dynamic data. I return the original validator from the .validate() call, and then do something like v.element('.email_addr'), but I can't seem to get that to work. Do you know if .element() will ever trigger a remote call?
Kevin J
Nevermind, I figured it out, I had an error in my selector..element() DOES retrigger the remote call, just needed the original validator object, which, in retrospect, makes complete sense.
Kevin J
Hmm, on further testing, it seems the 2nd part of the question is still unsolved - can't seem to trigger the remote call on an unchanged field. Will mark this question complete and ask it separately.Thanks
Kevin J
+1  A: 

Found the solution to the second part of my question:

 $(".email_addr").removeData("previousValue");

will remove the cache of the remote request, and allow the remote request to be triggered again, using .element().

Thus my code is as follows:

$("select.group_id").change(function() {
    $(".email_addr").removeData("previousValue"); //clear cache when changing group
    $("#customer_form").data('validator').element('.email_addr'); //retrigger remote call
    //my validator is stored in .data() on the form
});

Solution was found here: solution

Kevin J