Javascript中的验证,显示跨度错误

slhcrj9b  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(145)

我已经成功地创建了JS表单的验证(欢迎您提出任何其他的实现方法),但是我想我在这里的逻辑中遗漏了一些东西。
如果我按下按钮验证表单,而整个表单都是空的,则只显示我创建的1个错误范围(始终是第一个),我如何才能正确地实现这一点,以便在单击按钮后显示表单中的所有错误?
JS功能:

function validateForm() {
    var errorText;
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    var emailAdd = document.getElementById("email").value;
    var phone = document.getElementById("phone").value;
    var span_error = document.getElementById("span_error");

    /*Span Style*/
    span_error.style.padding = "2px 5px";
    span_error.style.display = "block";
    span_error.style.background = "#f9a5a5";
    span_error.style.color = "#666";
    
    
    if(firstName.length < 2){
        errorText = "Please enter a valid name";
        span_error.innerHTML = errorText;
        return false;
    }

    if(lastName.length < 2){
        errorText = "Please enter a valid name";
        span_error.innerHTML = errorText;
        return false;
    }
    /*isNan == is not a number , or the phone length is not equal to 10*/
    if(isNaN(phone) || phone.length != 9){
        errorText = "Please Enter valid Phone Number";
        span_error.innerHTML = errorText;
        return false;
    }

    if(emailAdd.indexOf("@") == -1 || emailAdd.length < 6){
        errorText = "Please Enter valid Email";
        span_error.innerHTML = errorText;
        return false;
    }

    alert("Good");
    return true;
}

部分表格举例:

<form action="" id="myform" onsubmit="return validateForm();">
<p>
        <input
          id="firstName"
          name="firstName"
          type="text"
          placeholder="Please type your first Name here"
        />
        <span id="span_error"></span>
</p>
<p>
        <input
          id="email"
          name="email"
          type="email"
          placeholder="Please type your email here"
        />
        <span id="span_error"></span>
      </p>
          <p>
        <input type="submit" value="Create My Account" id="submit" />
      </p>

</form>
0yg35tkg

0yg35tkg1#

这种处理代码的方式很烦人-因为如果你在验证表单时有任何错误,它会抛出错误**(NOT RETURNING FALSE)**,这会导致提交表单-
使用js添加eventListener进行提交,并使用e.preventDefault()方法。
顺便说一下,我把你的验证形式在尝试捕捉块,并得到这个错误;

TypeError: Cannot read property 'value' of null
at validateForm (index.html?firstName=mehran&email=:x@x.com)
at x (index.html?firstName=mehran&email=:x@x.com)
at HTMLFormElement.onsubmit (index.html?firstName=mehran&email=:x@x.com)

这似乎是你的一行有错误.它导致立即提交.
我删除了你的错误,它是这样工作的:
enter image description here

相关问题