与隐藏字段一起进行表单验证

时间:2013-07-05 17:44:24

标签: jquery validation

美好的一天。感谢Derek和Ross的大力帮助,我设法将表格与验证选项放在一起。关于这一点的具体问题是该页面包含3个表单,根据下拉列表,只显示一个表单。一切似乎完全不同于一件事。我无法提交表单,因为在其他2个隐藏表单中包含未填充的字段。我怎样才能克服这个问题?我认为这是向jquery添加一个在验证过程中忽略隐藏元素的部分的问题。但不幸的是我不知道该怎么做。下面的代码:

HTML:

    <select id='selector'>
    <option value='opt1' id="opt1">Quote Request</option>
    <option value='opt2' id="opt2">General Enquiry</option>
    <option value='opt3' id="opt3">Feedback</option>
</select>

<form action="" method="post" id="form1" class="form" action="scripts/form-quote.php">
        <ul>
            <li>
                <label for="name">Name</label>
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>
            </li>
            <li>
                <label for="email">E-mail</label>
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>
            </li>
            <li>
                <label for="msg">Message</label>
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Please specify your requirements" class="required"></textarea>
            </li>
            <li>
                <label for="ad">Referrer</label>
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />
            </li>
        </ul>
        <button type="submit" class="submit">Request a quote</button>

</form>

<form action="" method="post" id="form2" class="form" action="scripts/form-general.php">
        <ul>
            <li>
                <label for="name">Name</label>
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>
            </li>
            <li>
                <label for="email">E-mail</label>
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>
            </li>
            <li>
                <label for="msg">Message</label>
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Please enter your message" class="required"></textarea>
            </li>
            <li>
                <label for="ad">Referrer</label>
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />
            </li>
        </ul>
        <button type="submit" class="submit">Send your message</button>

</form>

<form action="" method="post" id="form3" class="form" action="scripts/form-feedback.php">

        <select>
            <option value='General feedback'>General feedback</option>
            <option value='Website feedback'>Website feedback </option>
            <option value='Services feedback'>Provided services feedback</option>
        </select>

        <ul>
            <li>
                <label for="name">Name</label>
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>
            </li>
            <li>
                <label for="email">E-mail</label>
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>
            </li>
            <li>
                <label for="msg">Message</label>
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>
            </li>
            <li>
                <label for="ad">Referrer</label>
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />
            </li>
        </ul>
        <button type="submit" class="submit">Send your feedback</button>

</form>

jQuery的:

 $(function () {
var addErrorMessage = function (field) {
        var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
        field.addClass('err').after(err);
    },
    clearError = function () {
        var t = $(this);
        if (t.hasClass('err')) {
            t.removeClass('err');
            t.next('p').empty().remove();
        }
    },
    isEmpty = function (str) {
        return str.trim().length < 1;
    },
    isValidEmail = function (str) {
        var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regexp.test(str);
    },
    validateForm = function () {
        var requiredFields = $(this).find('.required'),
            email = $('#email'),
            fieldsValidate = true;

        // check that required fields are not empty
        requiredFields.each(function () {
            var t = $(this);
            if (isEmpty(t.val())) {
                fieldsValidate = false;
                if (!t.hasClass('err')) {
                    addErrorMessage(t);
                }
            }
        });

        // check that email is valid
        if (!isValidEmail(email.val().trim())) {
            fieldsValidate = false;
            if (!email.hasClass('err')) {
                addErrorMessage(email);
            }
        }
        return fieldsValidate;
    };

$('input, textarea').keyup(clearError);
$('#form1').submit(validateForm);




var $select = $("#selector");
$select.change(function () {
    if ($('#selector option:selected').attr("id") == "opt1") {
        if ($('#form1').is(":hidden")) {
            $('#form1').fadeIn(500);
        }
        $('#form2').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt2") {
        if ($('#form2').is(":hidden")) {
            $('#form2').fadeIn(500);
        }
        $('#form1').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt3") {
        if ($('#form3').is(":hidden")) {
            $('#form3').fadeIn(500);
        }
        $('#form1').hide();
        $('#form2').hide();
    }
});
});

jsFiddle here

2 个答案:

答案 0 :(得分:2)

Fiddle

我花了一些时间来修复。你的代码有一些问题。对于不同形式的字段,您具有相同的ID,因此当您提交表单时,即使您在第2或第3页写作,他也总是从第一个表单中获取字段。 我在你的函数中添加了一个参数,并在提交按钮上添加了一个click功能。有一些更小的东西,我纠正了但忘了沿途的东西。我将keyup更改为blur。如果人们使用自动填充功能,那么它更加用户友好,如果您不喜欢,请更改回来。

可能需要修复一些小问题。但我想你想要的就是这里 我添加了一些console.log();这对你将来的调试是一个好主意:)

HTML:

<select id='selector'>
    <option value='opt1' id="opt1">Quote Request</option>
    <option value='opt2' id="opt2">General Enquiry</option>
    <option value='opt3' id="opt3">Feedback</option>
</select>
<form method="post" id="form1" class="form" action="scripts/form-quote.php">
    <ul>
        <li>
            <label for="name">Name</label>
            <input id="namef1" name="name" type="text" placeholder="Name" class="required" />
        </li>
        <li>
            <label for="email">E-mail</label>
            <input id="emailf1" name="email" type="text" placeholder="E-mail" class="required" />
        </li>
        <li>
            <label for="msg">Message</label>
            <textarea id="msgf1" name="msg" cols="43" rows="8" placeholder="Please specify your requirements" class="required"></textarea>
        </li>
        <li>
            <label for="ad">Referrer</label>
            <input id="adf1" name="ad" type="text" placeholder="Where did you hear about us?" />
        </li>
    </ul>
    <button type="submit" class="submit">Request a quote</button>
</form>
<form method="post" id="form2" class="form" action="scripts/form-general.php">
    <ul>
        <li>
            <label for="name">Name</label>
            <input id="namef2" name="name" type="text" placeholder="Name" class="required" />
        </li>
        <li>
            <label for="email">E-mail</label>
            <input id="emailf2" name="email" type="text" placeholder="E-mail" class="required" />
        </li>
        <li>
            <label for="msg">Message</label>
            <textarea id="msgf2" name="msg" cols="43" rows="8" placeholder="Please enter your message" class="required"></textarea>
        </li>
        <li>
            <label for="ad">Referrer</label>
            <input id="adf2" name="ad" type="text" placeholder="Where did you hear about us?" />
        </li>
    </ul>
    <button type="submit" class="submit">Send your message</button>
</form>
<form method="post" id="form3" class="form" action="scripts/form-feedback.php">
    <select>
        <option value='General feedback'>General feedback</option>
        <option value='Website feedback'>Website feedback</option>
        <option value='Services feedback'>Provided services feedback</option>
    </select>
    <ul>
        <li>
            <label for="name">Name</label>
            <input id="namef3" name="name" type="text" placeholder="Name" class="required" />
        </li>
        <li>
            <label for="email">E-mail</label>
            <input id="emailf3" name="email" type="text" placeholder="E-mail" class="required" />
        </li>
        <li>
            <label for="msg">Message</label>
            <textarea id="msgf3" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>
        </li>
        <li>
            <label for="ad">Referrer</label>
            <input id="adf3" name="ad" type="text" placeholder="Where did you hear about us?" />
        </li>
    </ul>
    <button type="submit" class="submit">Send your feedback</button>
</form>

JS:

var addErrorMessage = function (field) {
    var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
    field.addClass('err').after(err);
},
clearError = function () {
    var t = $(this);
    if (t.hasClass('err')) {
        t.removeClass('err');
        t.next('p').empty().remove();
    }
},
isEmpty = function (str) {
    return str.trim().length < 1;
},
isValidEmail = function (str) {
    var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regexp.test(str);
},
fieldsValidate = false;

function validateForm(e) {
    console.log('validate start');
    var requiredFields = jQuery(e).find('.required');
    var email = jQuery(e).find('input[name="email"]');
    var emailValue = email.val();
    console.log(emailValue+' mail val');
    fieldsValidate = true;
    // check that required fields are not empty
    requiredFields.each(function () {
        var t = $(this);
        if (isEmpty(t.val())) {
            fieldsValidate = false;
            if (!t.hasClass('err')) {
                addErrorMessage(t);
            }
        }
    });

    // check that email is valid
    console.log(isValidEmail(emailValue) + ' valid?');

    if (!isValidEmail(emailValue)) {
        fieldsValidate = false;
        if (!email.hasClass('err')) {
            addErrorMessage(email);
            console.log('mail NOT ok');
        }
    }
    console.log(fieldsValidate + ' before return');
    return fieldsValidate;
};

$('input, textarea').blur(clearError);

$(".submit").click(function() { return validateForm(this.form) });

var $select = $("#selector");
$select.change(function () {

    if ($('#selector option:selected').attr("id") == "opt1") {
        if ($('#form1').is(":hidden")) {
            $('#form1').fadeIn(500);
        }
        $('#form2').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt2") {
        if ($('#form2').is(":hidden")) {
            $('#form2').fadeIn(500);
        }
        $('#form1').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt3") {
        if ($('#form3').is(":hidden")) {
            $('#form3').fadeIn(500);
        }
        $('#form1').hide();
        $('#form2').hide();
    }
});

答案 1 :(得分:0)

如果表单不是动态的,您只需检查id并拒绝任何应该为空的匹配隐藏元素。