Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

javascript - jQuery Validate: Validate that one field, or both fields of a pair are required

I have a form that I am trying to validate that has two fields:

<div class="entryForm">
    <div class="formField">
        <label for="fieldEmailAddress">Email address:</label>
        <input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
    </div>
    <div class="formField">
        <label for="fieldMobileNumber">Mobile number:</label>
        <input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
    </div>
</div>

Here's my jQuery Validation wireup:

<script type="text/javascript">
    $(document).ready(function () {
        $('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
    });
</script>

What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can bypass the Validate plugin and do a check like the following:

$("#form1").submit(function() {
    var email = $('#fieldEmailAddress');
    var phone = $('#fieldMobileNumber');

    if(email.val() == '' && phone.val() == '') {
        alert('Fill out both fields');
    }
    else if(email.val() == '') {
        alert('Email, please...');
    }
    else if(phone.val() == '') {
        alert('Phone, please...');      
    }
    else {
        alert('Yay!');
    }   
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...