jQuery validate plugin require field if another field has a value and vice versa

拥有回忆 提交于 2019-12-17 22:37:53

问题


I am using the jQuery validate plugin to validate my form. I would like to tie several pairs of fields together such that if one field has a value, the other is required to have a value also. Essentially both fields (both text inputs) must either both have a value or both not have a value. Is anyone aware of a good way to accomplish this?


回答1:


if you look at the "rules" section's example code in the documentation page, there is a depends field you can set.

something like the following (this is right off my head, not tested):

...
secondInput: {
    required: function(element){
            return $("#firstInput").val()!="";
        }
}
....



回答2:


Just for clarification this is what I ended up doing based on Erico's answer:

    firstInput: {
        required: function(element){
            return $("#secondInput").val().length > 0;
        }
    },
    secondInput: {
        required: function(element){
            return $("#firstInput").val().length > 0;
        }
    }

Each input is now dependent on the other and will only be required if the other has a value.



来源:https://stackoverflow.com/questions/10406089/jquery-validate-plugin-require-field-if-another-field-has-a-value-and-vice-versa

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