JQuery 验证:如果两个可选字段都已填写,则验证失败?

JQuery Validation : Fail if two fields both optional are filled out?

我有一个要验证的表单,它有两个可选字段:

<label><b>URL Webcam Image:</b></label>
<p></p>
<input type="text" name="photo" id="photo" class="input"  />
<p></p>
<label><b>Upload</b></label>
    <br/><span>JPG, max. 200 kb</span> 
 <input type='file' name='uploaded_file' id="uploaded_file" /> 
<p></p>

如果两个字段都已填写,验证应该会失败,如果只填写其中一个字段或两个字段都为空,则应该没问题 我找不到具有 Jquery 验证的方法来实现这一点。我发现的所有内容都具有必需的条件,但我不希望它出现在这两个字段中

您必须使用 the addMethod() method 编写新的自定义规则。

$.validator.addMethod('notBoth', function (value, element, param) {
    return this.optional(element) || ($(element).is(':filled') && $('[name="' + param + '"]').is(':blank'));
}, "you must leave one of these blank");

$('#myform').validate({
    rules: {
        foo: {
            notBoth: 'bar'
        },
        bar: {
            notBoth: 'foo'
        }
    } 
});

演示:http://jsfiddle.net/uv23hgr7/

您还需要使用 groups and errorPlacement 选项将两个错误消息合并为一个并将其放置在您的布局中。

这会检查两个图像数据字段是否都有值。如果只有一个填写,则触发真正的提交:

    var orig = $('#uploaded_file').get(0).outerHTML;
    window.validatePic = function () {
        valid = !($('#photo').val() && $('#uploaded_file').val());
        if (valid) {
            $('#realSubmit').click();
        } else {
            alert('Please choose only one image.');
            $('#photo').val('');
            $('#uploaded_file').after(orig);
            $('#uploaded_file').remove();
        }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>... other form options
    <br>
    <br>
    <label><b>URL Webcam Image:</b>

        <label />
        <p></p>
        <input type="text" name="photo" id="photo" class="input" />
        <p></p>
        <label><b>Upload</b>

            <label />
            <br/><span>JPG, max. 200 kb</span> 
            <input type='file' name='uploaded_file' id="uploaded_file" />
            <p></p>
            <button type="button" onclick="validatePic()">Submit</button>
            <button type="submit" id="realSubmit" style="display: none">hidden</button>
</form>