Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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!');
    }   
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...