简体   繁体   中英

contact form require to fill one of two fields

I want to create a contact form in WordPress where one of two fields must be filled to send. For example - e-mail and telephone number are required, but if a user fills just one field then it will be ok.

This depends on how you want to validate it.

PHP? You could do something like:

if ( empty($_POST['name1']) && empty($_POST['name2']) ) {
    // Error message
}

JS? You could do something like:

var input1Val = document.getElementsByName('name1')[0].value;
var input2Val = document.getElementsByName('name2')[0].value;

if ( input1Val.length > 0 || input2Val.length > 0 ) {
    // Allow submission
}
`$(document).ready(function () {

    $('#forgot_pass_form').validate({ // initialize the plugin
        groups: {
            names: "uname email"
        },
        rules: {
            uname: {
                require_from_group: [1, ".send"]
            },
            email: {
                require_from_group: [1, ".send"]
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

    jQuery.extend(jQuery.validator.messages, {
        require_from_group: jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")
    });

});`

And html

<form action="#" class="send_form" id="forgot_pass_form" method="POST">
    <fieldset>
        <div class="send_row">
            <label class="padding-top10">Email</label>
            <input type="text" class="send_email send" id="email" name="email"
            /> <em>You need to type an email address</em>

        </div>
        <div class="send_row option">OR</div>
        <div class="send_row">
            <label class="padding-top10">Username</label>
            <input type="text" class="send_username send" id="uname"
            name="uname" />
        </div>
        <div class="send_row send_submitforgotuser">
            <input type="submit" value="Submit" />
        </div>
    </fieldset>
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>

Working demo: http://jsfiddle.net/sgmvY/1/

Validating form without js, needs developing your own form plugin.

Here is one article about it.

Change validation logic to be aware of logical OR in these two fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM