Javascript正则表达式电子邮件验证

时间:2015-04-26 10:55:03

标签: javascript php regex validation email

我使用正则表达式来测试电子邮件输入。它会在提交错误的电子邮件(例如没有@或.com)时发出警报但是当我按下确定警告时,它仍会将电子邮件发送到指向send_msg.php页面的电子邮件地址它不应该..我是Javascript和PHP的新手所以我还在学习..我知道 if 子句应该遵循 else 但我不知道如果是真的,如何让它发布电子邮件。我可以如何让它只是在电子邮件输入字段下方显示一条消息,而不是让它发出警报?

<script>
function checkEmail(inputvalue){    
var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(pattern.test!=(inputvalue)){  
         alert("Please enter a valid email address");  
         return false;


}

}   

<form id="contact-form" name= "form1 "action="send_msg.php" method="post">
        <h3>Get in touch</h3>
        <h4>Fill in the form below, and we'll get back to you within 24 hours.</h4>
        <div>
            <label>
                <span>Name: </span>
                <input placeholder="Please enter your name" name="name" type="text" tabindex="1" required autofocus>
            </label>
        </div>
        <div>
            <label>
                <span>Email: </span>
                <input placeholder="Please enter your email address" name="email" type="email" tabindex="2" required>
            </label>
        </div>

        <div>
            <label>
                <span >Message: </span>
                <textarea placeholder="Include all the details you can" name="message" tabindex="5" size= "35" maxlength= "255"></textarea>
            </label>
        </div>
        <div>
            <button name="submit" type="submit" onClick="checkEmail(document.contact-form.email.value)" id="contact-submit">Send Email</button>
        </div>
    </form>

2 个答案:

答案 0 :(得分:0)

假设正则表达式验证没问题,您可以阻止表单提交,只需执行以下操作:

<form onsubmit="return checkEmail(document.contact-form.email.value);" id="contact-form" name= "form1 "action="send_msg.php" method="post">
...
</form>

从提交按钮中删除onClick。如果正则表达式函数在有效时返回true,如果无效则返回false,而表单只在电子邮件输入中包含有效数据时才提交。

希望这有帮助。

让我知道。

<强>干杯!

答案 1 :(得分:0)

看起来你的函数有语法错误就这样使用

MyClass