JavaScript验证问题——HTML表单即使不完整也要提交

JavaScript Validation Issue - HTML form submits even when incomplete

本文关键字:提交 问题 验证 HTML 表单 JavaScript      更新时间:2023-09-26

我是JavaScript的新手,正在努力把我的头绕在这个上面。

我有一个HTML表单,其中一些必需的输入字段具有onblur验证。我想修复我的代码,以便在没有用户填写这些必需字段的情况下提交表单时,显示错误消息,而不是像当前一样实际提交表单。

我意识到也有人问过类似的问题,但我无法实施建议的方法,我已经研究了几天了。我还需要一个纯JavaScript方法,那么如何确保在单击提交按钮时,所有空的必填字段都会抛出错误消息呢?

这是我第一次发布问题-我希望我已经涵盖了所有内容,如果我需要包括任何其他内容,请告诉我!提前谢谢。

<form id="contact-form" method="POST" action="contact.html" novalidate>
  <p>Text</p>
  <div class="form-group">
    <select name="flights" size="1">
      <option value="" disabled selected hidden>Select Flight</option>
      <option value="helicopter">Helicopter</option>
      <option value="aerobatic">Aerobatic</option>
      <option value="tramping">Tramping</option>
      <option value="amphibian">Amphibian</option>
      <option value="glider">Glider</option>
      <option value="private-charter">Private Charter</option>
    </select>
  </div>
  <div class="form-group">
    <label>Flight Duration</label>
    <br>
    <select name="flight-duration" size="1">
      <option value="" disabled selected hidden>Select Duration</option>
      <option value="helicopter">1 Hour</option>
      <option value="tramping">2 Hours</option>
      <option value="amphibian">3 Hours</option>
      <option value="glider">Custom</option>
    </select>
  </div>
  <div class="form-group">
    <label>Booking Date</label>
    <br>
    <select id="dayDropDown">
    </select>
    <select id="monthDropDown">
    </select>
    <select id="yearDropDown">
    </select>
  </div>
  <div class="form-group">
    <label for="firstname"></label>
    <input id="firstname" type="text" onblur="blur()" name="firstname" placeholder="First Name" required autofocus minlength="2">
    <span id="firstname-error"></span>
  </div>
  <div class="form-group">
    <label for="lastname"></label>
    <input id="lastname" type="text" name="lastname" placeholder="Last Name" required minlength="2">
    <span id="lastname-error"></span>
  </div>
  <div class="form-group">
    <label for="phone"></label>
    <input id="phone" type="tel" name="phone" placeholder="Phone Number" required minlength="8">
    <span id="phone-error"></span>
  </div>
  <div class="form-group">
    <label for="email"></label>
    <input id="email" type="email" name="email" placeholder="Enter valid email address" required>
    <span id="email-error"></span>
  </div>
  <div class="form-group">
    <label for="country"></label>
    <input id="country" type="text" name="country" placeholder="Country" required minlength="2">
    <span id="country-error"></span>
  </div>
  <div class="form-group">
    <textarea placeholder="What can we do for you?"></textarea>
  </div>
  <div class="form-group">
    <button class="submit" type="submit">Submit</button>
  </div>
</form>
/****************
     *FORM-VALIDATION*
     ****************/
//convert user input to upper case
function addFormValidation(theForm) {
  if (theForm === null || theForm.tagName.toUpperCase() !== 'FORM') {
    throw new Error("expected first parameter to addFormValidation to be a FORM.");
  }
  theForm.noValidate = true;
  theForm.addEventListener('submit', function (evt) {
    var isError = false;
    var elements = this.elements;
    for (var i = 0; i < elements.length; i += 1) {
      if (!isFieldValid(elements[i])) {
        isError = true;
      }
    }
    if (isError) {
      evt.preventDefault();
    }
  });
  function isFieldValid(field) {
    var errorMessage = "";
    function isFieldValid(field) {
      if (!needsToBeValidated(field)) {
        return true;
      }
      if (field.id.length === 0 || field.name.length === 0) {
        console.error("error: ", field);
        throw new Error("found a field that is missing an id and/or name attribute." +
                        " name should be there. id is required for determining the field's error message element.");
      }
      field.classList.remove('invalid');
      var errorSpan = document.querySelector('#' + field.id + '-error');
      if (errorSpan === null) {
        console.error("error: ", field);
        throw new Error("could not find the '#" + field.id + "-error' element. It's needed for error messages if #" + field.id + " is ever invalid.");
      }
      errorSpan.classList.remove('danger');
      errorSpan.innerHTML = "";
      if (field.minLength > 0 && field.value.length < field.minLength) {
        errorMessage = "Must be " + field.minLength + " or more characters long.";
      }
      if (field.maxLength > -1 && field.value.length > field.maxLength) {
        errorMessage = "Must be " + field.maxLength + " characters or less.";
      }
      if (field.type === "email" && !isEmail(field.value)) {
        errorMessage = "This should be a valid email address.";
      }
      if (field.required && field.value.trim() === "") {
        errorMessage = "This field is required.";
      }
      if (errorMessage !== "") {
        field.classList.add('invalid');
        errorSpan.classList.add('danger');
        errorSpan.innerHTML = errorMessage;
        return false;
      }
      return true;
    }

    //fields that do not require validation
    //        function needsToBeValidated(field) {
    //            return ['submit', 'reset', 'button', 'hidden', 'radio', 'fieldset', 'select'].indexOf(field.type) === -1;
    //        }
    function needsToBeValidated(field) {
      return ['submit', 'reset', 'button', 'hidden', 'fieldset'].indexOf(field.type) === -1;
    }
    //email regx pattern to ensure email input is a valid email
    function isEmail(input) {
      return input.match(/^([a-z0-9_.'-+]+)@(['da-z.'-]+)'.([a-z'.]{2,})$/);
    }
    //add onblur validation to provide error/success info for user
    var elements = theForm.elements;
    for (var j = 0; j < elements.length; j++) {
      elements[j].addEventListener('blur', function () {
        isFieldValid(event.target);
      })
    };
  }
  //wait for content to load before loading form
  document.addEventListener('DOMContentLoaded', function () {
    addFormValidation(document.querySelector('#contact-form'))
  });
  /***********************************************
         * Implemented this date selector script for use on contact form:
         * Drop Down Date select script- by JavaScriptKit.com
         * This notice MUST stay intact for use
         * Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
         ***********************************************/
  var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
  function populatedropdown(dayfield, monthfield, yearfield) {
    var today = new Date()
    var dayfield = document.getElementById(dayfield)
    var monthfield = document.getElementById(monthfield)
    var yearfield = document.getElementById(yearfield)
    for (var i = 0; i < 31; i++)
      dayfield.options[i] = new Option(i, i + 1)
      dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day
      for (var m = 0; m < 12; m++)
        monthfield.options[m] = new Option(monthtext[m], monthtext[m])
        monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
        var thisyear = today.getFullYear()
        for (var y = 0; y < 20; y++) {
          yearfield.options[y] = new Option(thisyear, thisyear)
          thisyear += 1
        }
    yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
  }
  //populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
  window.onload = function () {
    populatedropdown("dayDropDown", "monthDropDown", "yearDropDown")
  }

你必须在你的代码中调用你的javascript验证函数。

<form name="" method="" onsumbmit="return myfunction()">
 <!-- Your code -->
</form>

在javascript代码中,如果一切正确,则返回true,否则返回false并显示适当的消息

function myfunction(){
    <!-- here your validation conditions -->>
    if(everything==ok)
    return true;
    else
    return false;
}

去掉表单上的novalidate属性