开发者

How to use jQuery to remotely validate a field that depends on another field in the form?

开发者 https://www.devze.com 2022-12-28 16:35 出处:网络
I have a form in which I am using remote validation t开发者_JS百科o check if an email address already exists in the database.However, the catch is that on this form, the user can select between severa

I have a form in which I am using remote validation t开发者_JS百科o 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.


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

The first part of my question was answered originally by @Jeffery To

All that needs to be done is to change the value of the parameter to a function, rather than just a value. Jeffery's example is copied below for future googlers:

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


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()?

0

精彩评论

暂无评论...
验证码 换一张
取 消