提问者:小点点

如何从w3schools向多步骤表单添加验证


我正在用w3schools的这篇教程创建一个多步骤表单,但是在教程中,只有一种通用类型的验证(它检查字段是否为空),这是不合适的。如何使文本和电子邮件的HTML验证(例如,最小,最大,长度)工作良好?如何自定义验证?我不想为表单中的每个字段编写验证,因为我在表单中有许多字段。

index.html

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
           
        <title>Personal</title>
        <link href="./css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="./css/all.css" rel="stylesheet" type="text/css" />
        <link href="./css/personal.css" rel="stylesheet" type="text/css" />
        <style> 
        </style>
    </head>

    <body>        
        <main>    
            <div class="container py-5">
                <form id="students-registration" class="jumbotron">

                  <div class="tab">
                    <h2 class="lead text-center">Demographic Information</h2>
                    <div class="form-row">
                      <div class="form-group col">
                        <input type="text" class="form-control form-control-sm" placeholder="Surname">
                      </div>
                      <div class="form-group col">
                        <input type="text" class="form-control form-control-sm" placeholder="First name">
                      </div>
                      <div class="form-group col">
                        <input type="text" class="form-control form-control-sm" placeholder="Middle name">
                      </div>
                    </div>
                  </div>
                                                                                       

                  <div class="tab">
                    <h2 class="lead text-center">Medicals</h2>                    
                      <div class="form-row col-md-4 pl-0 pb-1">
                        <label for="">How would you rate your health</label>
                        <select class="form-control form-control-sm" name="" id="">
                          <option value="Good">Good</option>
                          <option value="Fair">Fair</option>
                          <option value="Poor">Poor</option>
                        </select>
                      </div>
                  </div>

                                        
                  <div style="overflow:auto;">
                    <div style="float:right;" class="p-2">
                      <button type="button" class="btn btn-sm btn-info" id="prevBtn">Previous</button>
                      <button type="button" class="btn btn-sm btn-success" id="nextBtn">Next</button>
                    </div>
                  </div>
                  
                  <!-- Circles which indicates the steps of the form: -->
                  <div style="text-align:center;margin-top:40px;">
                    <span class="step"></span>
                    <span class="step"></span>
                    <span class="step"></span>
                    <span class="step"></span>
                  </div>

                </form>
                
            </div>
        </main>


        <footer> 
        
        </footer>
        
        
        <script src="./js/jquery-3.3.1.min.js"></script>
        <script src="./js/popper.min.js"></script>
        <script src="./js/bootstrap.min.js"></script>
        <script src="./js/scripts.js"></script>
        

    </body>

</html>


scripts.js

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }
  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form...
  if (currentTab >= x.length) {
    // ... the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {

    if (y[i].hasAttribute("required")) {
      // If a field is empty...
      if (y[i].value() == "") {
        // add an "invalid" class to the field:
        y[i].className += " invalid";
        // and set the current valid status to false:
        valid = false;
      }
      
    } else {

    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}



$(document).ready(() => {
  $('#prevBtn').click( (e) => { 
    //e.preventDefault();
    nextPrev(-1);
  });

  $('#nextBtn').click( (e) => { 
    //e.preventDefault();
    nextPrev(1);
    console.log('working');
  });

});

共2个答案

匿名用户

  • 您实际上不需要任何javascript验证,只要使用适当的type/pattern/min/max/required/maxlength/minlength属性,浏览器就可以用客户端自己的语言为您验证表单。
  • 但是要进行验证,您必须使用submit事件和event.PreventDefault()来阻止默认行为离开,而不是使用button click事件。这样浏览器将使用约束验证
  • 来验证表单

如果您不喜欢约束验证的外观,那么您可以使用验证api并查看诸如input.validy对象等内容

匿名用户

您已经在html上准备好了它作为输入的属性

但是为了实现,您必须稍微更改代码,使所有的逻辑都包含在a标记中,并使用一个按钮提交表单,然后使用e.preventDefault(),就像另一个答案告诉您的那样

有关更多信息,请检查此

https://developer.mozilla.org/en-us/docs/web/html/element/input#属性

您可以只使用此属性来要求输入不能为空

 <input type="text" required >

“required”如下^^^

对于minlength,只需使用“minlength”

<input type="text" required minlength="5">

像这样^^^

输入类型电子邮件将检查您是否输入电子邮件ish字符串

<input type="email" >

像这样^^^

将接受具有acb@dddd.com的任何字符串

希望有帮助!!!

但如果您需要更多的验证,那么您必须创建您自己的:(

也许这个视频能帮到你

https://www.youtube.com/watch?v=in0nb0abauk