首页 > 解决方案 > 我可以在表单验证中使用参数吗?

问题描述

我正在尝试实现一个简单的表单验证,但我无法以某种方式使其与参数一起工作。

这是只有一个输入的代码:

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)

标签: javascripthtml

解决方案


首先,getElementById 返回一个 HTMLInputElement 而不是元素的实际 ID。

const firstName = document.getElementById("first-name"); // typeof HTMLInputElement

正如其他评论所提到的,您的事件侦听器绑定到 的返回值validate(firstName),即voidor 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
}

推荐阅读