javascript - 电子邮件验证客户端

标签 javascript client-side email-validation

<form action="#" method="post" id="book-list">
 <div class="form-group">
   <label for="email">Email</label>
   <input type="text" id="email" class="form-control">
 </div>
 <input type="submit" value="Add" class="btn btn-primary btn-block">
</form>
<script type="text/javascript">
 function isEmail(email){
    return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z](2,4))$/.test(email);
    }   
 const form = document.querySelector('#book-list').addEventListener('submit',(e) =>{
    e.preventDefault();
    const inputEmail = document.querySelector('#email').value;
    if(isEmail(inputEmail) === false ){
      console.log('you lost');
      document.querySelector('#email').focus();
      return false;
    }else{
      console.log('you win');
      return true
    }

});
</script>

Playing around with this email validation, is there anything wrong with the code? even I filled the field with the proper email address like myname@gmail.com it kept printing you lost result instead of printing the you win, is it because the form submit?

最佳答案

如果您想让 html5 为您进行验证,您可以使用输入 type='email',如果该字段无效,提交将不会触发。

否则,您可以将正则表达式稍微更改为下面的

([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})

关于javascript - 电子邮件验证客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943487/

相关文章:

javascript - asp.net 将 json 发布到 Controller

javascript - 如何设置 typeorm .env 文件?

java - 根据 RFC5322 和 https ://en. 进行电子邮件 ID 验证 wikipedia.org/wiki/Email_address

javascript while() 循环创建一行单元格而不是表格

javascript - 如何在 javascript 中加载 html 页面

java - 如何将服务器端的数据自动推送到swing客户端?

javascript - 确保按需加载图像

ios - 使用适用于 iOS 的 firebase 验证电子邮件

javascript - Iron Router 和 Meteor 中的服务器端路由