如何在Jquery中验证电子邮件?

时间:2010-09-08 01:18:55

标签: jquery forms validation email-validation

我写了以下联系表单验证脚本。如何验证电子邮件字段?

<style type="text/css">
    div.contactForm { width:370px; margin:0 auto; }
    form.contactUs label { display:block; }
    form.contactUs input { margin-bottom:10px; }
    input.submit { margin-top:10px; }
    input.error { background:#FF9B9B; border:1px solid red; }
    div.errorMessage { color:#f00; padding:0 0 20px; }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $('.errorMessage').hide();
        $('.submit').click(function() {

            var name = $('input.name').val();
            var email = $('input.email').val();
            var phone = $('input.phone').val();

            if (name == '') {
                $('input.name').addClass('error');
                $('input.name').keypress(function(){
                    $('input.name').removeClass('error');
                });
            }
            if (email == '') {
                $('input.email').addClass('error');
                $('input.email').keypress(function(){
                    $('input.email').removeClass('error');
                });
            }
            if (phone == '') {
                $('input.phone').addClass('error');
                $('input.phone').keypress(function(){
                    $('input.phone').removeClass('error');
                });
            }
            if (name == '' || email == '' || phone == '') {
                $('.errorMessage').fadeIn('medium');
                return false;
            }

        });
    });
</script>

<div class="contactForm">

<h2>Contact Us</h2>

<div class="errorMessage">Please enter all required fields.</div>

<form action="http://google.com" method="post" class="contactUs">

    <label>Name <em>(required)</em></label>
    <input type="text" name="name" class="name" size="30" />

    <label>Email <em>(valid email required)</em></label>
    <input type="text" name="email" class="email" size="30" />

    <label>Phone <em>(required)</em></label>
    <input type="text" name="phone" class="phone" size="30" />

    <label>Message</label>
    <textarea name="message" cols="40" rows="10"></textarea>

    <br />
    <input type="submit" name="submit" value="Submit" class="submit" />

</form>

</div><!--contactForm-->

修改

通过验证,我的意思是输入的值必须在适当的位置包含“@”和“。”。

此外,我不想使用任何其他插件。

5 个答案:

答案 0 :(得分:34)

如果您不想使用任何插件,可以使用RegEx。

var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(valueToTest))
    // Do whatever if it passes.
else
    // Do whatever if it fails.

这将为您提供最多的电子邮件。关于validating emails with RegEx.

的有趣读物

您可以在此处测试脚本:http://jsfiddle.net/EFfCa/

答案 1 :(得分:2)

如果你真的不想使用插件,我发现这个方法非常好:

function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if( !emailReg.test( email ) ) {
        return false;
    } else {
        return true;
    }
}

JSFIDDLE

http://thejimgaudet.com/articles/support/web/jquery-e-mail-validation-without-a-plugin/

答案 2 :(得分:1)

我目前正在使用ketchup进行表单验证。还有bassassist's plugin。检查插件,它将为您节省数小时的正则表达式编写代码。

答案 3 :(得分:1)

将此input.email块更改为:

            if (email == '') {
            $('input.email').addClass('error');
            $('input.email').keypress(function(){
                $('input.email').removeClass('error');
            });
            $('input.email').focusout(function(){
                $('input.email').filter(function(){
                    return this.value.match(/your email regex/);
                }).addClass('error');
            });
        }

阐释: 将焦点操作添加到input.email表单元素,使用RFC822标准验证电子邮件字符串。如果无法通过则添加“错误”类。

我没有在浏览器上对此进行过测试,但它应该适用于jQuery&gt; 1.4。

编辑:我删除了正则表达式,将您最喜欢的那个放在那里。

答案 4 :(得分:1)

以下代码对我有用。

<input type="text" id="Email" />

$('#Email').change(function () {
        var status = false;
        var email = $('#Email').val();
        var emailLength = email.length;
        if (email != "" && emailLength > 4) {
            email = email.replace(/\s/g, "");  //To remove space if available
            var dotIndex = email.indexOf(".");
            var atIndex = email.indexOf("@");

            if (dotIndex > -1 && atIndex > -1) {   //To check (.) and (@) present in the string
                if (dotIndex != 0 && dotIndex != emailLength && atIndex != 0 && atIndex != emailLength && email.slice(email.length - 1) != ".") {   //To check (.) and (@) are not the firat or last character of string
                    var dotCount = email.split('.').length
                    var atCount = email.split('@').length

                    if (atCount == 2 && (dotIndex - atIndex > 1)) { //To check (@) present multiple times or not in the string. And (.) and (@) not located subsequently
                        status = true;
                        if (dotCount > 2) {    //To check (.) are not located subsequently
                            for (i = 2; i <= dotCount - 1; i++) {
                                if (email.split('.')[i-1].length == 0) {
                                    status = false;
                                }
                            }
                        }
                    }
                }
            }

        }

        $('#Email').val(email);
        if (!status) {
            alert("Wrong Email Format");
        }
    });