如何检查电子邮件地址是否包含@符号和'。'。在html和javascript中

时间:2018-04-18 21:19:06

标签: javascript html

我正在对用户的一些输入执行一些验证检查。我想知道如何检查用户输入的电子邮件是否包含@符号和'。'以及@符号前后的字符。在此先感谢您的回答。

<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
    function showInput() {
      var comment = document.getElementById("com").value;
      var first = document.getElementById("fname").value;
      var last = document.getElementById("lname").value;
      var dateOfVisit = document.getElementById("date").value;
      var firstError = document.getElementById('firstNameError');
      var lastError = document.getElementById('lastNameError');
      var displayEl = document.getElementById('displayname');

      if (!first) {
        firstError.setAttribute('style', 'display: block; color: red');
      } else {
        firstError.setAttribute('style', 'display: none;');
      }
      if (!last) {
        lastError.setAttribute('style', 'display: block; color: red');
      } else {
        lastError.setAttribute('style', 'display: none;');
      }
      displayEl.innerHTML = 
        first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
    }   
</script>

<title>Great Pyramid of Giza</title>

</head>

<body>

<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
  First Name:<br>
  <input type = "text" name="firstname" id="fname"><br>
  <span style="display: none;" id="firstNameError">First name is required!</span>
  Last Name:<br>
  <input type = "text" name="lastname" id="lname"><br>
  <span style="display: none;" id="lastNameError">Last name is required!</span>
  Email Address:<br>
  <input type = "text" name="email"><br>
  Date of Visit:<br>
  <input type = "text" name="date" id="date"><br>
  Comment:<br>
  <input type = "text" name="comment" size="70" id="com"><br>
</form> 

<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>


</body>

</html> 

1 个答案:

答案 0 :(得分:1)

您可以创建电子邮件输入并对其进行验证,而不是使用任何正则表达式...

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

console.log(isEmail('admin@example.com'))
console.log(isEmail('@example.com'))

但为什么要打扰?只需使用<input type="email">并跳过所有javascript nonsens

<form>
  <input type="text" name="firstname" required autocomplete="given-name">
  <input type="text" name="lastname" required autocomplete="family-name">
  <input type="email" name="email" autocomplete="email">
  <input type="date" min="2018-04-21" name="date">
  <textarea name="comment"></textarea>
  <input type="submit">
</form> 

ps,使用form.onsubmit代替btn.onclick(更好的方式)

详细了解constraint validationinputs