[英]Can I use an event listener to validate an email address after its entered with JavaScript?
所以我试图验证在用户完成将他们的电子邮件输入到 input 元素后是否输入了有效的电子邮件地址。 如果他们没有输入有效的电子邮件,它会将元素边框更改为红色,如果他们输入了正确的电子邮件,它只会留下边框。
如何在不提交表单的情况下执行此操作? 我希望它在用户输入电子邮件时或在他们取消对元素的关注时发生。
这是我到目前为止所拥有的,但它不起作用。
谢谢!
const emailInput = document.querySelector("#email");
const emailInputValue = emailInput.value;
emailInput.addEventListener("input", (e) => {
if( /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(emailInputValue) != true) {
emailInput.style.border = "thin solid red"
} else {
emailInput.style.border = "thin solid #0000FF"
}
})
<div id="email_div">
<input type="email" name="email" id="email" placeholder="Email" maxlength="50">
<label for="email" id="email_text">This field is required in order to receive an email confirmation.</label>
</div>
这是当输入失焦时有效的东西!
<input type="email" name="email" placeholder="Email Address" id="email_field" onChange="return emailValidation()">
<span id="email-error"></span>
<script>
function emailValidation()
{
value = document.getElementById('email_field').value;
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
lastpos=value.length-1;
if (apos < 1 || dotpos-apos < 2 || lastpos-dotpos > 3 || lastpos-dotpos < 2){
document.getElementById("email-error").innerHTML = "Invalid Email Address";
return false;
} else {
return true;
}
}
</script>
因为您是在事件监听器之前获取输入的值,所以它将始终为空。 如果要停止发送表单,请使用preventDefault()
const emailInput = document.querySelector("#email"); emailInput.addEventListener("input", (e) => { const emailInputValue = e.currentTarget.value; if( /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$/.test(emailInputValue) != true) { emailInput.style.border = "thin solid red" } else { emailInput.style.border = "thin solid #0000FF" } })
<div id="email_div"> <input type="email" name="email" id="email" placeholder="Email" maxlength="50"> <label for="email" id="email_text">This field is required in order to receive an email confirmation.</label> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.