Как добавить проверку в многоступенчатую форму из w3schools

#javascript #html #css #bootstrap-4

#javascript #HTML #css #bootstrap-4

Вопрос:

Я создаю многоступенчатую форму с помощью этого руководства из 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 amp;amp; !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');
  });

});
  

Как мне предотвратить переход формы на следующую страницу, если эта конкретная страница не является действительной?

Комментарии:

1. Я заметил, что вы используете jquery, поэтому эти плагины должны вам помочь jqueryvalidation.org если вы все еще не знаете, как это сделать, дайте мне знать

Ответ №1:

  • На самом деле вам не нужна проверка javascript, браузер может проверить форму для вас на собственном языке клиента, если вы используете соответствующие атрибуты type / pattern / min / max / required / maxlength / minlength .
  • Но для того, чтобы проверка состоялась, вы должны вместо использования события нажатия кнопки использовать событие отправки и event.preventDefault() прекратить переход к поведению по умолчанию. Таким образом, браузер будет проверять форму с помощью проверки ограничений

если вам не нравится внешний вид проверки ограничений, вы можете использовать api проверки и среди прочего просматривать такие вещи, как input.validity object

Комментарии:

1. Когда я нажимаю кнопку «Следующая страница», она не проверяет эту страницу. Именно это я и хочу сделать

Ответ №2:

у вас есть готовый html-код в качестве атрибута ввода

но для того, чтобы это произошло, вам нужно будет немного изменить код и внести всю логику в теги и отправить форму с помощью кнопки, а затем e.preventDefault(), как сказано в другом ответе

для получения дополнительной информации проверьте это

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes

вы можете просто использовать этот атрибут, чтобы требовать, чтобы ввод не мог быть пустым

  <input type="text" required >
  

«требуется» вот так ^^^

для минимальной длины просто используйте атрибут «minlength»

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

вот так ^^^

тип ввода email будет проверять, вводите ли вы строку адреса электронной почты

 <input type="email" >
  

вот так ^^^

примет любую строку, которая имеет acb@dddd.com

надеюсь, это поможет!!!

но если вам нужна дополнительная проверка, вам придется создать свою собственную: (

возможно, это видео сможет вам помочь

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

Комментарии:

1. Большое спасибо, но как мне предотвратить переход формы на следующую страницу, если эта конкретная страница не является действительной?

2. вам нужно присвоить кнопке атрибут type=»submit» и перехватить событие отправки формы с помощью функции, а затем написать e.preventDefault() …. письменными словами гораздо сложнее объяснить процесс, поэтому я рекомендую посмотреть видео в концеиз моего ответа youtube.com/watch?v=In0nB0ABaUk

3. если вы хотите, я могу попробовать поработать с вами над этим в видеовызове