【问题标题】:How to make JavaScript form validation update while user types如何在用户输入时更新 JavaScript 表单验证
【发布时间】:2018-05-11 01:42:44
【问题描述】:

我有一个表单验证脚本,它会在用户提交表单时警告他们表单存在问题。我想知道如何在用户键入并修复错误时删除警告。例如,如果您提交一个空字段,则会出现“不能为空白”的文本,我希望用户开始在输入字段中输入时该文本消失,从而使该字段不再为空白。任何帮助表示赞赏,并有很长的路要走。谢谢!

HTML

                <!-- Individual Form -->
                <form id="individual" action="#" method="POST" onsubmit="return validateStudentSignUpForm()" autocomplete="off">

                    <!-- Individual First Name -->
                    <div class="form-group">
                        <span id="firstid" class="text-warning"></span>
                        <input class="form-control" id="first" name="first" type="text" placeholder="First name" />
                    </div>

                    <!-- Individual Last Name -->
                    <div class="form-group">
                        <span id="lastid" class="text-warning"></span>
                        <input class="form-control" id="last" name="last" type="text" placeholder="Last name" />
                    </div>

                    <!-- Individual Email -->
                    <div class="form-group">
                        <span id="email1id" class="text-warning"></span>
                        <input class="form-control email" id="email1" name="email" type="text" placeholder="Email" />
                    </div>

                    <!-- Individual Password -->
                    <div class="form-group">
                        <span id="password1id" class="text-warning"></span>
                        <input class="form-control" id="password1" name="password" type="password" placeholder="Password" />
                    </div>

                    <!-- Individual's Birthday -->
                    <div class="form-group">
                        <label>Birthday</label>
                        <div class="form-inline">
                            <!-- Month -->
                            <select id="month1" name="month" onChange="changeDate1(this.options[selectedIndex].value);" class="form-control month-space">
                                <option value="na">Month</option>
                                <option value="1">January</option>
                                <option value="2">February</option>
                                <option value="3">March</option>
                                <option value="4">April</option>
                                <option value="5">May</option>
                                <option value="6">June</option>
                                <option value="7">July</option>
                                <option value="8">August</option>
                                <option value="9">September</option>
                                <option value="10">October</option>
                                <option value="11">November</option>
                                <option value="12">December</option>
                            </select>

                            <!-- Day -->
                            <select name="day" id="day1" class="form-control day-space">
                                <option value="na">Day</option>
                            </select>

                            <!-- Year -->
                            <select name="year" id="year1" class="form-control year-space">
                                <option value="na">Year</option>
                            </select>

                            <span id="date1id" class="text-warning"></span>
                        </div>
                    </div>

                    <button type="submit" name="submit" class="btn blue-button">Confirm</button>

                </form>

                <!-- Parent Form -->
                <form id="parent" class="hidden" action="#" method="POST" onsubmit="return validateStudentSignUpForm()" autocomplete="off">

                    <!-- Parent's First Name -->
                    <div class="form-group">
                        <span id="parent-firstid" class="text-warning"></span>
                        <input class="form-control" id="parent-first" name="parent-first" type="text" placeholder="Parent's first name" />
                    </div>

                    <!-- Parent's Last Name -->
                    <div class="form-group">
                        <span id="parent-lastid" class="text-warning"></span>
                        <input class="form-control" id="parent-last" name="parent-last" type="text" placeholder="Parent's last name" />
                    </div>

                    <!-- Parent Email -->
                    <div class="form-group">
                        <span id="email2id" class="text-warning"></span>
                        <input class="form-control" id="email2" name="email" type="text" placeholder="Email" />
                    </div>

                    <!-- Parent Password -->
                    <div class="form-group">
                        <span id="password2id" class="text-warning"></span>
                        <input class="form-control" id="password2" name="password" type="password" placeholder="Password" />
                    </div>

                    <!-- Child's First Name -->
                    <div class="form-group">
                        <span id="child-firstid" class="text-warning"></span>
                        <input class="form-control" id="child-first" name="child-first" type="text" placeholder="Child's first name" />
                    </div>

                    <!-- Child's Birthday -->
                    <div class="form-group">
                        <label>Child's birthday</label>
                        <div class="form-inline">
                            <!-- Month -->
                            <select id="month2" name="month" onChange="changeDate2(this.options[selectedIndex].value);" class="form-control month-space">
                                <option value="na">Month</option>
                                <option value="1">January</option>
                                <option value="2">February</option>
                                <option value="3">March</option>
                                <option value="4">April</option>
                                <option value="5">May</option>
                                <option value="6">June</option>
                                <option value="7">July</option>
                                <option value="8">August</option>
                                <option value="9">September</option>
                                <option value="10">October</option>
                                <option value="11">November</option>
                                <option value="12">December</option>
                            </select>

                            <!-- Day -->
                            <select name="day" id="day2" class="form-control day-space">
                                <option value="na">Day</option>
                            </select>

                            <!-- Year -->
                            <select name="year" id="year2" class="form-control year-space">
                                <option value="na">Year</option>
                            </select>

                            <span id="date2id" class="text-warning"></span>
                        </div>
                    </div>

                    <button type="submit" name="submit" class="btn blue-button">Confirm</button>
                </form>

                <p class="text-center" id="small">By signing up you agree to our
                    <a href="#">Terms of Use</a> and
                    <a href="#">Privacy Policy</a>
                </p>
            </div>
        </div>
    </div>

JavaScript

function validateStudentSignUpForm() {
    var first = document.getElementById("first").value;
    var last = document.getElementById("last").value;
    var email1 = document.getElementById("email1").value;
    var password1 = document.getElementById("password1").value;
    var parentFirst = document.getElementById("parent-first").value;
    var parentLast = document.getElementById("parent-last").value;
    var childFirst = document.getElementById("child-first").value;
    var email2 = document.getElementById("email2").value;
    var password2 = document.getElementById("password2").value;
    var month1 = document.getElementById("month1").value;
    var day1 = document.getElementById("day1").value;
    var year1 = document.getElementById("year1").value;
    var month2 = document.getElementById("month2").value;
    var day2 = document.getElementById("day2").value;
    var year2 = document.getElementById("year2").value;
    var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var nameFilter = /^([^0-9]*)$/;

    // First name can't be blank
    if (first == "") {
        document.getElementById("first").className = document.getElementById("first").className + " error";
        document.getElementById("firstid").innerHTML = "Can't be blank";
    }

    // First name can't be a number
    else if (!nameFilter.test(first)) {
        document.getElementById("first").className = document.getElementById("first").className + " error";
        document.getElementById("firstid").innerHTML = "Can't have numbers";
    }

    // First name can't be longer than 50 characters
    else if (first.length > 50) {
        document.getElementById("first").className = document.getElementById("first").className + " error";
        document.getElementById("firstid").innerHTML = "Name is too long";
    }

    // Last name can't be blank
    if (last == "") {
        document.getElementById("last").className = document.getElementById("last").className + " error";
        document.getElementById("lastid").innerHTML = "Can't be blank";
    }

    // Last name can't be a number
    else if (!nameFilter.test(last)) {
        document.getElementById("last").className = document.getElementById("last").className + " error";
        document.getElementById("lastid").innerHTML = "Can't have numbers";
    }

    // Last name can't be longer than 50 characters
    else if (last.length > 50) {
        document.getElementById("last").className = document.getElementById("last").className + " error";
        document.getElementById("lastid").innerHTML = "Name is too long";
    }

    // Email can't be blank
    if (email1 == "") {
        document.getElementById("email1").className = document.getElementById("email1").className + " error";
        document.getElementById("email1id").innerHTML = "Can't be blank";
    }

    // Email test
    else if (!emailFilter.test(email1)) {
        document.getElementById("email1").className = document.getElementById("email1").className + " error";
        document.getElementById("email1id").innerHTML = "Use a proper email format";
    }

    // Password can't be blank
    if (password1 == "") {
        document.getElementById("password1").className = document.getElementById("password1").className + " error";
        document.getElementById("password1id").innerHTML = "Can't be blank";
    }

    // Password has to be 6 characters
    else if (password1.length < 6) {
        document.getElementById("password1").className = document.getElementById("password1").className + " error";
        document.getElementById("password1id").innerHTML = "Password must be 6 characters long";
    }

    // Password can't be longer than 100 characters
    else if (password1.length > 100) {
        document.getElementById("password1").className = document.getElementById("password1").className + " error";
        document.getElementById("password1id").innerHTML = "Password must be less than 100 characters long";
    }

    // Parent first can't be blank
    if (parentFirst == "") {
        document.getElementById("parent-first").className = document.getElementById("parent-first").className + " error";
        document.getElementById("parent-firstid").innerHTML = "Can't be blank";
    }

    // Parent first can't be a number
    else if (!nameFilter.test(parentFirst)) {
        document.getElementById("parent-first").className = document.getElementById("parent-first").className + " error";
        document.getElementById("parent-firstid").innerHTML = "Can't have numbers";
    }

    // Parent first can't be longer than 50 characters
    else if (parentFirst.length > 50) {
        document.getElementById("parent-first").className = document.getElementById("parent-first").className + " error";
        document.getElementById("parent-firstid").innerHTML = "Name is too long";
    }

    // Parent last can't be blank
    if (parentLast == "") {
        document.getElementById("parent-last").className = document.getElementById("parent-last").className + " error";
        document.getElementById("parent-lastid").innerHTML = "Can't be blank";
    }

    // Parent last can't be a number
    else if (!nameFilter.test(parentLast)) {
        document.getElementById("parent-last").className = document.getElementById("parent-last").className + " error";
        document.getElementById("parent-lastid").innerHTML = "Can't have numbers";
    }

    // Parent last can't be longer than 50 characters
    else if (parentLast.length > 50) {
        document.getElementById("parent-last").className = document.getElementById("parent-last").className + " error";
        document.getElementById("parent-lastid").innerHTML = "Name is too long";
    }

    // Child first can't be blank
    if (childFirst == "") {
        document.getElementById("child-first").className = document.getElementById("child-first").className + " error";
        document.getElementById("child-firstid").innerHTML = "Can't be blank";
    }

    // Child first can't be a number
    else if (!nameFilter.test(childFirst)) {
        document.getElementById("child-first").className = document.getElementById("child-first").className + " error";
        document.getElementById("child-firstid").innerHTML = "Can't have numbers";
    }

    // Child first can't be longer than 50 characters
    else if (childFirst.length > 50) {
        document.getElementById("child-first").className = document.getElementById("child-first").className + " error";
        document.getElementById("child-firstid").innerHTML = "Name is too long";
    }

    // Email can't be blank
    if (email2 == "") {
        document.getElementById("email2").className = document.getElementById("email2").className + " error";
        document.getElementById("email2id").innerHTML = "Can't be blank";
    }

    // Email2 test
    else if (!emailFilter.test(email2)) {
        document.getElementById("email2").className = document.getElementById("email2").className + " error";
        document.getElementById("email2id").innerHTML = "Use a proper email format";
    }

    // Password can't be blank
    if (password2 == "") {
        document.getElementById("password2").className = document.getElementById("password2").className + " error";
        document.getElementById("password2id").innerHTML = "Can't be blank";
    }

    // Password has to be 6 characters
    else if (password2.length < 6) {
        document.getElementById("password2").className = document.getElementById("password2").className + " error";
        document.getElementById("password2id").innerHTML = "Password must be 6 characters long";
    }

    // Password can't be longer than 100 characters
    else if (password2.length > 100) {
        document.getElementById("password2").className = document.getElementById("password2").className + " error";
        document.getElementById("password2id").innerHTML = "Password must be less than 100 characters long";
    }

    // Month1 can't be default
    if (month1 === "na") {
        document.getElementById("month1").className = document.getElementById("month1").className + " error";
        document.getElementById("date1id").innerHTML = "Choose a valid date";
    }

    // Day1 can't be default
    if (day1 === "na") {
        document.getElementById("day1").className = document.getElementById("day1").className + " error";
        document.getElementById("date1id").innerHTML = "Choose a valid date";
    }

    // Month1 can't be default
    if (year1 === "na") {
        document.getElementById("year1").className = document.getElementById("year1").className + " error";
        document.getElementById("date1id").innerHTML = "Choose a valid date";
    }

    // Month2 can't be default
    if (month2 === "na") {
        document.getElementById("month2").className = document.getElementById("month2").className + " error";
        document.getElementById("date2id").innerHTML = "Choose a valid date";
    }

    // Day2 can't be default
    if (day2 === "na") {
        document.getElementById("day2").className = document.getElementById("day2").className + " error";
        document.getElementById("date2id").innerHTML = "Choose a valid date";
    }

    // Year2 can't be default
    if (year2 === "na") {
        document.getElementById("year2").className = document.getElementById("year2").className + " error";
        document.getElementById("date2id").innerHTML = "Choose a valid date";
    }

    return false;
}


.error {
    border: 2px solid red;
}

【问题讨论】:

    标签: javascript html css forms validation


    【解决方案1】:

    onfocus 事件添加到您的输入字段,这将删除验证警告消息

    【讨论】:

    • 我添加了 onfocus="return validateStudentSignUpForm"。然而,这并没有奏效。关于为什么的任何想法?
    • 输入为onfocus时不需要调用验证函数。只需清除验证消息。这是基于您的代码的快速示例:jsfiddle.net/qoz55to0 点击输入。
    • 我对你的意思有些困惑。你能给我举一个 onfocus 的例子吗
    • 更新了之前的评论。希望对你有帮助
    【解决方案2】:

    你可以通过这样做来解决这个问题:

    • 聆听 onfocus 输入。
    • 保留一个变量,说明是否显示警报 (true/false)
    • 通过询问该变量是否为真来处理 onfocus,如果是,则将其从 de DOM 中删除,如果不是,则不执行任何操作。

    【讨论】:

    • 我可以举一个变量说明是否显示警报的示例
    • 您可以有一个名为“isMessageOpen”的变量,默认情况下它的值为 false,并且每当您在代码中显示该消息时,您也会将该变量更新为 true。最后,当用户关闭消息(点击事件)时,将变量更改为 false。
    【解决方案3】:

    我想知道如何在用户键入并修复错误时删除警告

    您需要对每个输入事件执行相同的验证。在您的代码中尝试以下更改:

    更改 1:将属性 oninput 附加到 form 标记

     <form id="individual" action="#" method="POST" onsubmit="return validateStudentSignUpForm()" oninput="return validateStudentSignUpForm()" autocomplete="off">
    

    更改 2:您需要重置错误消息。

    document.getElementById("firstid").innerHTML = ""; /* reset, so on for the rest */
    if (first == "") {
            document.getElementById("first").className = document.getElementById("first").className + " error";
            document.getElementById("firstid").innerHTML = "Can't be blank";
    }
    

    【讨论】:

      【解决方案4】:

      我建议使用像这样的单独函数进行这些验证。使用 jQuery 看起来像这样:

      var isFirstNameValid = false;
      var isLastNameValid = false;
      var isPasswordValid = false;
      
      $("#first").change(function(){
          if(this.value.length < 1){
              $(this).css("border","1px solid red");
              $("#firstid").html("Can't be blank");
              isFirstNameValid = false;
          }
          else{
              $("#firstid").html("");
              $(this).css("border","1px solid black");
              isFirstNameValid = true;
          }
      });
      
      //here is another example you can use to check your validation:
      
      $("#password1").focusout(function(){
          if(this.value.length < 6){
              $(this).css("border","1px solid red");
              $("#password1id").html("must be longer than 6 char");
              isPasswordValid = false;
          }
          else if(this.value.length > 100){
              $(this).css("border","1px solid red");
              $("#password1id").html("must be less than 100 char");
              isPasswordValid = false;
          }
          else{
              $(this).css("border","1px solid black");
               $("#password1id").html("");
               isPasswordValid = true;
          }
      
      });
      
      //or you can use this example to check your validation on every input you 
      // make in the field:
      
      $("#last").on("input", function(){
         if(this.value.length < 1){
              $(this).css("border","1px solid red");
              $("#lastid").html("Can't be blank");
              isLastNameValid = false;
          }
          else if(this.value.length > 50){
              $(this).css("border","1px solid red");
              $("#lastid").html("must be less than 50 char");
              isLastNameValid = false;
          }
          else{
              $(this).css("border","1px solid black");
              $("#lastid").html("");
              isLastNameValid = true;           
          }
      
      });
      
      
      function validateStudentSignUpForm() {
      // check if your validations are true
      if(isFirstNameValid == true && isLastNameValid == true && 
      isPasswordValid  ==  true){
      
      var first = document.getElementById("first").value;
      var last = document.getElementById("last").value;
      var password1 = document.getElementById("password1").value;
      // any futre logic or code here
      // you dont need the validations here in this funcion anymore
      
      }}
      

      要使用 jQuery,你只需要这样写:

      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      

      在 HTML 文件中的 javascript 之前。

      另一个不使用 jQuery 的解决方案可能是这样的:

      var firstName = document.getElementById('first');
      var firstNameDisplay = document.getElementById('firstid');
      
      firstName.addEventListener("oninput", function(){
            firstNameDisplay.innerHTML = "";
      });
      

      每次您开始在输入字段中输入时,它都会清除消息“不能为空”。您必须对所有输入字段执行此操作。 阅读此内容可能会对您有所帮助。 https://www.w3schools.com/jsref/event_oninput.asp

      【讨论】:

      • 如果使用 jQuery $(selector).on('input',...) 最适合您键入验证
      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2015-08-27
      • 1970-01-01
      • 2023-03-23
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多