在javascript中使用onblur事件验证电子邮件

时间:2014-03-18 11:44:47

标签: javascript regex forms validation email

如何在JavaScript中验证电子邮件。我有点击事件来检查值是否为空 - 请参见下文,但如何在一个检查正则表达式的单独函数中检查onblur事件

var e =document.forms["myForm"]["email_18"].value;
if(e==null ||e=="" || e=="someone@example.com")
{
    document.getElementById("emailMessage").innerHTML = "*Please enter an  email";
    flag = false;
}

文字框:

<input type="email" class="text" name="email_18" id="amf-input-email_18" value="" placeholder="someone@example.com" maxlength="255" onkeyup="if(this.length>255) this.value=this.value.substr(0, 255)"></div></div>

2 个答案:

答案 0 :(得分:5)

使用正则表达式进行电子邮件检查:

function checkEmail(str)
{
    var re = /^(([^<>()[\]\\.,;:\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,}))$/;
    if(!re.test(str))
    alert("Please enter a valid email address");
}

将onblur事件添加到输入框:

<input type="email" class="text" name="email_18" id="amf-input-email_18" value="" placeholder="someone@example.com" maxlength="255" onblur="checkEmail(this.value)"></div></div>

答案 1 :(得分:0)

将青年文本框的onblur属性设置为函数名称,如下所示

<input type="email" class="text" name="email_18" id="amf-input-email_18" value="" placeholder="someone@example.com" maxlength="255" onkeyup="if(this.length>255) this.value=this.value.substr(0, 255)" onblur="checkemail(this.value)">

编写javascript函数如下:

function checkemail(email)
{
   var regex=/^[a-zA-Z0-9\.\_]+\@@{1}[a-zA-Z0-9]+\.\w{2,4}$/;
   if(!regex.test(email))
   {
       alert('Please enter valid email id');
    }
 }