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