javascript - 我可以使用事件侦听器在使用 JavaScript 输入电子邮件地址后对其进行验证吗?
问题描述
因此,一旦用户完成将电子邮件输入到输入元素中,我将尝试验证是否输入了有效的电子邮件地址。如果他们没有输入有效的电子邮件,它会将元素边框更改为红色,如果他们确实输入了正确的电子邮件,它只会留下边框。
在不提交表格的情况下如何做到这一点?我希望它在用户键入电子邮件时或在他们取消关注元素时发生。
这是我到目前为止所拥有的,但它不起作用。
谢谢!
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>
推荐阅读
- r - 如何在 Shiny 模块生成的 DiagrammeR 输出中找到单击的元素
- sqlite - SQLite - 如何使用一个命令行读取脚本文件
- postgresql - 本地 Postgres 数据库到 Google Cloud PostgreSQL Github
- python - 为 ML 分类处理列中的无限/大值
- php - 使用 json_encode 数据设置输入字段默认值
- python - 如何根据多个变量定位数据帧的子组并仅替换原始数据帧中该子组的值?
- c - 使用 void 指针连接字符串
- triggers - 是否可以从 Power App 触发 ADF 管道?
- node.js - Httprequest 未收到来自快速路由器的响应
- ruby-on-rails - 使用 exq 和 Sidekiq 在 rails 和 phoenix 之间进行通信