javascript - 我可以在表单验证中使用参数吗?
问题描述
我正在尝试实现一个简单的表单验证,但我无法以某种方式使其与参数一起工作。
这是只有一个输入的代码:
const firstName = document.getElementById("first-name");
const nameRegex = /^[a-zA-Z]{2,15}$/;
firstName.addEventListener("blur", validate(firstName));
function validate(id) {
let re = "";
switch (id) {
case firstName:
re = nameRegex;
break;
case lastName:
re = nameRegex;
break;
case email:
re = emailRegex;
break;
case password:
re = passwordRegex;
break;
}
if (!re.test(id.value)) {
id.parentElement.classList.add("error");
id.parentElement.nextElementSibling.classList.remove("hide");
} else {
id.parentElement.classList.remove("error");
id.parentElement.nextElementSibling.classList.add("hide");
}
}
看起来代码无法进入 id.value 字段。
作为参考,此代码工作正常:
function validateFirstName() {
if (!nameRegex.test(firstName.value)) {
firstName.parentElement.classList.add("error");
firstName.parentElement.nextElementSibling.classList.remove("hide");
} else {
firstName.parentElement.classList.remove("error");
firstName.parentElement.nextElementSibling.classList.add("hide");
}
}
谁能指出我正确的方向?(我只想用香草JS)
解决方案
首先,getElementById 返回一个 HTMLInputElement 而不是元素的实际 ID。
const firstName = document.getElementById("first-name"); // typeof HTMLInputElement
正如其他评论所提到的,您的事件侦听器绑定到 的返回值validate(firstName)
,即void
or undefined
。
您需要做的是告诉事件侦听器blur
在元素上发生事件时触发该函数。
firstName.addEventListener("blur", validate); // Bind your entire validate function instead of the return value
现在您必须更改验证函数内部的逻辑,以区分不同的输入。
function validate(event) {
// event.target is your entire element
// event.target.value is the current value
// event.target.id is the string id ie. first-name
switch(event.target.id) {
case 'first-name'
re = nameRegex; // Assigns your nameRegex
break;
}
if(re === '') {
return; // Do nothing as we have no regex to validate with
}
// Your other code here
}
推荐阅读
- mysql - mysql用户定义函数如何知道找到了选定的行?
- python - 在 python 代码中插入复杂的函数
- javascript - 作业需要帮助!首次在 Ionic 上使用 API
- python - 循环遍历熊猫数据框以比较字符串是否匹配附加行的值
- typescript - 为什么无法通过 Deno TypeScript 中的窗口访问全局声明的变量?
- javascript - 如何记住 setInterval 中的过去值?
- python - 在 python 中使用 split() 函数创建新列
- azure - Terraform 映射并将值传递给模块
- arduino - 我的 ESP32 代码在 Arduino uno 之间建立 UART 通信是否正确?
- awk - 返回在 bash 中至少连续出现 n 次模式的行