如何验证first_name而不是last_name

时间:2013-10-26 06:45:33

标签: jquery jquery-validate

如何检查first_name值是否存在(如果last_name仅存在)? 如果我将first_name保留为空并且输入last_name ..则在first_name中显示错误。如果last_name为空,则不显示错误

下面是html和验证脚本

<form id="myform">
    <input type="text" id="first_name" name="first_name" value="">
        <input type="text" id="last_name" name="last_name" value="">
    <input type="submit" />
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            first_name:{ required:true },
            last_name:{ required:true }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

       $('#myform').validate({ // initialize the plugin
            rules: {
                first_name:{ 
                    required: {
                       depends: function(element) {
                            return $('#last_name').val().length > 0;
                        }
                       }
                    } 
                },
            },
            submitHandler: function (form) { // for demo
                alert('valid form submitted'); // for demo
                return false; // for demo
            }
        });