jQuery Validation - require field only if another field is filled [duplicate]

谁说我不能喝 提交于 2019-12-12 06:36:26

问题


Possible Duplicate:
JQuery validation-select required if checkbox checked

I'm validating a form with jQuery Validation. I'm trying to come up with a rule that will validate fields as required if a field in a particular set of fields is filled:

<form id="donate-form">
    <input type="text" name="full_name" required="required" /><br />
    <input type="text" name="address1" /><br />
    <input type="text" name="address2" /><br />
    <input type="text" name="city" /><br />
    <select name="state">
        <option value="">- State -</option>
        <option value="va">Virginia</option>
        <option value="md">Maryland</option>
    </select><br />
    <input type="text" name="zip" />
    <input type="submit" name="submit" />
</form>

All address fields are optional unless someone fills out address1, city, state, or zip, then they should all be required.


回答1:


Example

Using depends, fill in your requirements.

var depends = function() {
    var vals = '';
    $('form > *').not(':eq(0)').each(function () {
        vals += $(this).val();
    });

    return vals.length > 0;
};

You should change the selectors to something more specific to fit your needs. ie not $('form')



来源:https://stackoverflow.com/questions/12484323/jquery-validation-require-field-only-if-another-field-is-filled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!