如何使input.error在所有领域工作?

时间:2014-02-26 11:57:14

标签: javascript jquery html css forms

http://jsfiddle.net/Nvt2h/

我正在使用此脚本将输入字段的详细信息发送到我的电子邮件中。正如您所看到的,如果输入不正确,则会有input.error以红色突出显示该字段。但是,这目前仅适用于Field 1和Field 4。

我如何在第2和第3栏上完成这项工作?

<form id="contact" name="contact" action="#" method="post">
<div class="form-group">
    <label for="msg">Field1:

    </label>
    <input name="msg" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
    <label for="id">Field2:</label>
    <input name="id" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
    <label for="pb">Field3:

    </label>
    <input name="pb" type="msg" class="form-control" id="pb">
</div>
<div class="form-group">
    <label for="email">Field4:</label>
    <input name="email" type="email" class="form-control" id="email">
</div>
<button id="send">Submit</button>

1 个答案:

答案 0 :(得分:0)

为这些输入字段添加minlength属性

<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2">

然后

function validateEmail(email) {
    var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return reg.test(email);
}

$(document).ready(function () {
    //$(".modalbox").fancybox();
    $("#contact").submit(function () {
        return false;
    });


    $("#send").on("click", function () {
        $('#contact input.error').removeClass('error');

        var emailval = $("#email").val();
        var mailvalid = validateEmail(emailval);
        if (mailvalid == false) {
            $("#email").addClass("error");
        }

        var minlen = $('#contact input[minlength]').filter(function(){
            return this.value.length < +$(this).attr('minlength')
        }).addClass('error').length;

        if (mailvalid == true && minlen == 0) {
            // if both validate we attempt to send the e-mail
            // first we hide the submit btn so the user doesnt click twice
            $("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");

            $.ajax({
                type: 'POST',
                url: 'send.php',
                data: $("#contact").serialize(),
                dataType: 'jsonp',
                success: function (data) {
                    if (data.result == true) {
                        $("#contact").fadeOut("fast", function () {
                            $(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>");
                        });
                    } else { /* if you want to handle mail send failed, put it here */
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // this is triggered if there's a problem getting the jsonp back from the server
                }
            });
        }
    });
});

演示:Fiddle