繁体   English   中英

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

[英]How to check whether an email address contains an @ sign and a '.'. in html and javascript

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

<!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> 

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

 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错误

<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 (更好)

阅读有关约束验证输入的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM