javascript中的电子邮件ID验证

时间:2017-06-09 11:57:45

标签: javascript validation email

我有两个域来检查有效的电子邮件ID是否检查正常,但是当我提供@@(双倍)时,它还需要有效的电子邮件ID。

如何检查并停止用户输入@@@

我检查有效电子邮件的代码

function validate() {

  if (email == "") {
    alert('Please Enter EmailId');
    document.getElementById("txtEmail").focus();
    return false;
  } else if (email.lastIndexOf("@") === 0 || !(email.endsWith("@ho.XXX.com") || email.endsWith("@YYY.com"))) {
    if (document.getElementById("txtEmail").value == "@ho.XXX.com" || document.getElementById("txtEmail").value == "@YYY.com") {
      alert("Please Enter Valid UserName before @");
      document.getElementById("txtEmail").focus();
      return false;
    }
    alert("Email Should be in @ho.XXX.com or @YYY.com");
    $("#txtEmail").val('');
    document.getElementById("txtEmail").focus();
    return false;
  }
}

3 个答案:

答案 0 :(得分:0)

您可以使用String.prototype.match()

email.match(/@/g).length

您的代码将是这样的:



if (email == ""){   
     alert('Please Enter EmailId');
     document.getElementById("txtEmail").focus();
     return false;
     }

    else if(email.match(/@/g) > 1 || !(email.endsWith("@ho.XXX.com") || email.endsWith("@YYY.com"))){
        if(document.getElementById("txtEmail").value=="@ho.XXX.com"||document.getElementById("txtEmail").value=="@YYY.com"){
         alert("Please Enter Valid UserName before @");
         document.getElementById("txtEmail").focus();
         return false;
    }
      alert("Email Should be in @ho.XXX.com or @YYY.com");
       $("#txtEmail").val('');
       document.getElementById("txtEmail").focus();
         return false; 
}




答案 1 :(得分:0)

不要重复自己:

function validate() {
  var email = $.trim($("#txtEmail").val());
  if (email === "" ||
    email.split("@").length !== 2 ||
    email.lastIndexOf("@") === 0 ||
   !email.endsWith("@ho.XXX.com") ||
   !email.endsWith("@YYY.com") ) {
     alert("Please Enter Valid UserName before @\nEmail Should be in   @ho.XXX.com or @YYY.com");
     $("#txtEmail").focus();
     return false;
   }
   return true; // allow whatever
}

答案 2 :(得分:0)

使用build in validator:

function emailValid(emailAddy){
  var email = document.createElement('input');
  email.type = 'email';
  email.value = emailAddy;
  return email.validity.valid; 
};

console.log (emailValid('ttt@gmx.de'));
console.log (emailValid('tt t@gm x.de'));