如何验证表单数据,然后通过 AJAX 发送,然后在同一页面上显示提交的结果

Posted

技术标签:

【中文标题】如何验证表单数据,然后通过 AJAX 发送,然后在同一页面上显示提交的结果【英文标题】:how to validate form data, then send via AJAX, then show the submitted results on the same page 【发布时间】:2020-05-11 14:59:01 【问题描述】:

我正在建立一个简单的单页表单网站。我的验证与我的 AJAX 请求一起工作并隐藏/显示提交的表单结果时遇到问题。这是我的问题:

    当我单击Begin 按钮打开注册表时,JS 验证已经触发,导致出现所有错误消息。我需要“开始”按钮来只打开表单而不触发 JS 验证。 验证未完全工作。将显示错误代码,但是,如果您单击带有错误消息(无效输入)的 Register 按钮,表单仍将提交。如果有任何错误消息,我需要不提交表单。 当我单击注册按钮时,尽管我使用了event.preventDefault() 函数,但页面仍在加载。如果没有错误,我需要注册按钮来发送数据,而不是重新加载页面,并隐藏注册表以显示提交数据的div(我没有在此代码中包含提交数据的div)。李>

注意:我使用的是 vanilla JS - AJAX 和 php

window.addEventListener('DOMContentLoaded', (event) => 

  // Open the Registration Form
  document.getElementById("beginButton").addEventListener("click", function() 
    document.body.classList.remove("begin");
  )


  window.addEventListener("load", function(event) 
    let fnameValid = fnameVerify();
    let lnameValid = lnameVerify();
    let emailValid = emailVerify();
    let dateOfBirthValid = dateOfBirthVerify();
    let nationOfOriginValid = nationOfOriginVerify();

    if (!(fnameValid && lnameValid && emailValid && dateOfBirthValid && nationOfOriginValid)) 
      event.preventDefault();
     else 

      function sendData() 
        const XHR = new XMLHttpRequest();

        // Bind the FormData object and the form element
        const FD = new FormData(form);

        // Define what happens on successful data submission
        XHR.addEventListener("load", function(event) 
          alert(event.target.responseText);
        );

        // Define what happens in case of error
        XHR.addEventListener("error", function(event) 
          alert('Oops! Something went wrong.');
        );

        // Set up our request
        XHR.open("POST", "validate.php");

        // The data sent is what the user provided in the form
        XHR.send(FD);
      

      // Access the form element...
      let form = document.getElementById("registrationForm");

      // ...and take over its submit event.
      form.addEventListener("submit", function(event) 
        event.preventDefault();
        sendData();
      );
      document.getElementById("registrationForm").addEventListener("submit")
      document.getElementById("beginButtonDiv").classList.add("hide");
      document.getElementById("registrationFormDiv").classList.add("hide");
      document.getElementById("serverMessageDiv").classList.add("hide");
      console.log("Success changing divs!");
    
  );

  // RegEx Synteax
  const nameFormat = /^[a-zA-Z ]+$/;
  const emailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w2,3)+$/;
  const dateFormat = /^\d4[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$/;

  // Event Hanlder Functions
  let firstName = document.getElementById("fname");
  let lastName = document.getElementById("lname");
  let email = document.getElementById("email");
  let dateOfBirth = document.getElementById('dateOfBirth');
  let nationOfOrigin = document.getElementById("nationOfOrigin");

  // Event Listeners for Error Messages '*'
  firstName.addEventListener("keyup", fnameVerify);
  lastName.addEventListener("keyup", lnameVerify);
  email.addEventListener("keyup", emailVerify);
  dateOfBirth.addEventListener("keyup", dateOfBirthVerify);
  nationOfOrigin.addEventListener("keyup", nationOfOriginVerify);

  // First Name Validation
  function fnameVerify() 
    let fname = document.forms["registrationForm"]["firstname"];
    let fnameErr = document.getElementById("fnameErr");

    // TODO: Split up the RegEx validation into min letters and only letters

    let error = "";
    if (fname.value == "") 
      error = " is required";
     else if (!fname.value.match(nameFormat)) 
      error = " only letters";
     else if (fname.value.length < 3) 
      error = " 3 letters min";
     else if (fname.value.length > 45) 
      error = " 45 letters max";
    

    if (error != "") 
      fname.classList.add("invalid");
      fnameErr.innerhtml = "*" + error;
      return false;
     else 
      fname.classList.remove("invalid");
      fnameErr.innerHTML = "*";
      return true;
    
  


  // Last Name Validation
  function lnameVerify() 
    let lname = document.forms["registrationForm"]["lastname"];
    let lnameErr = document.getElementById("lnameErr");

    let error = "";
    if (lname.value == "") 
      error = " is required";
     else if (!lname.value.match(nameFormat)) 
      error = " only letters";
     else if (lname.value.length < 3) 
      error = " 3 letters min";
     else if (lname.value.length > 45) 
      error = " 45 letters max";
    

    if (error != "") 
      lname.classList.add("invalid");
      lnameErr.innerHTML = "*" + error;
      return false;
     else 
      lname.classList.remove("invalid");
      lnameErr.innerHTML = "*";
      return true;
    
  

  // Email Validation
  function emailVerify() 
    let email = document.forms["registrationForm"]["email"];
    let emailErr = document.getElementById("emailErr");

    let error = "";
    if (email.value == "") 
      error = " is required";
     else if (!email.value.match(emailFormat)) 
      error = " invalid email format";
    

    if (error != "") 
      email.classList.add("invalid");
      emailErr.innerHTML = "*" + error;
      return false;
     else 
      email.classList.remove("invalid");
      emailErr.innerHTML = "*";
      return true;
    
  

  // Date of Birth Validation
  function dateOfBirthVerify() 
    let dateOfBirth = document.forms["registrationForm"]["dateOfBirth"];
    let dateOfBirthErr = document.getElementById("dateOfBirthErr");

    let error = "";
    if (dateOfBirth.value == "") 
      error = " is required";
     else if (!dateOfBirth.value.match(dateFormat)) 
      error = " invalid date";
    

    if (error != "") 
      dateOfBirth.classList.add("invalid");
      dateOfBirthErr.innerHTML = "*" + error;
      return false;
     else 
      dateOfBirth.classList.remove("invalid");
      dateOfBirthErr.innerHTML = "*";
      return true;
    
  

  // Nation of Origin Validation
  function nationOfOriginVerify() 
    let nationOfOrigin = document.forms["registrationForm"]["nationOfOrigin"];
    let nationOfOriginErr = document.getElementById("nationOfOriginErr");

    let error = "";
    if (nationOfOrigin.value == "") 
      error = " is required";
     else if (nationOfOrigin.value.match("000")) 
      error = " select a country";
    

    if (error != "") 
      nationOfOrigin.classList.add("invalid");
      nationOfOriginErr.innerHTML = "*" + error;
      return false;
     else 
      nationOfOrigin.classList.remove("invalid");
      nationOfOriginErr.innerHTML = "*";
      return true;
    
  
);
/* Hiding the "Begin" button and showing the Registration form */

body.begin #registerFormDiv,
body:not(.begin) #serverMessageDiv,
body:not(.begin) #beginButtonDiv 
  display: none;



/* Hide class for hiding the register form and begin button upon form submission */

.hide 
  display: none;
<!-- Begin Button Div -->
<div id="beginButtonDiv">
  <button id="beginButton" class="buttonRise">BEGIN</button>
</div>

<!-- Regirstration Form Div -->
<div id="registerFormDiv">
  <form name="registrationForm" id="registrationForm" method="POST">

    <!-- Required Fields -->
    <span id="required" class="error">* All fields are required</span>
    <br><br>

    <div id="fullname">
      <!-- Fullname Labels & Errors -->
      <div id="fullnameLabels">
        <!-- First Name -->
        <div>
          <label id="firstLabel" for="fname">First Name</label>
          <span id="fnameErr" class="error">*</span>
        </div>
        <!-- Last Name -->
        <div>
          <label id="lastLabel" for="lname">Last Name</label>
          <span id="lnameErr" class="error">*</span>
        </div>
      </div>

      <!-- Fullname Inputs -->
      <div id="fullnameInputs">
        <input type="text" id="fname" name="firstname" placeholder="e.g. Reggie" />
        <input type="text" id="lname" name="lastname" placeholder="e.g. Rocket" />
      </div>
    </div>

    <!-- Email -->
    <label for="email">Email</label>
    <span id="emailErr" class="error">*</span>
    <br>
    <input type="email" id="email" name="email" placeholder="regge.rocket@dr.com" />

    <!-- Date of Birth -->
    <label for="dateOfBirth">Date of Birth</label>
    <span id="dateOfBirthErr" class="error">*</span>
    <br>
    <input type="date" id="dateOfBirth" name="dateOfBirth" placeholder="<?php echo date('Y-m-d'); ?>" max="5000-12-31" min="1900-01-01" />

    <!-- Nation of Origin -->
    <label for="nationOfOrigin">Nation of Origin</label>
    <span id="nationOfOriginErr" class="error">*</span>
    <br>
    <select id="nationOfOrigin" name="nationOfOrigin">
      <option value="000">--Select--</option>
      <option value="AF">Afghanistan</option>
    </select>

    <!-- Submit Button -->
    <input type="submit" class="buttonRise" value="Register" id="submitButton" name="submitButton">

  </form>
</div>

非常感谢您对这三个问题的任何帮助!!!

【问题讨论】:

【参考方案1】:
    发生初始错误是因为您验证了窗口上load 事件中的所有字段。我的猜测是您希望将所有这些逻辑移动到 submit 事件侦听器中。因为您只想发送所有字段都有效的数据,对吗?因此,请移除 load 事件处理程序并将其替换为您提交的表单的 submit 事件侦听器。 见 (1) 另见 (1)

考虑将您的代码修改为以下结构。它将函数定义保持在同一级别以防止出现意外行为,例如不在 load 事件侦听器回调中定义函数。

当有人提交时,您应该验证您的表单。那一刻,一切都应该由用户填写。如果验证成功,则发送数据。如果不是,则显示错误。

我希望这能让你朝着正确的方向前进。

window.addEventListener('DOMContentLoaded', function() 

  beginButton.addEventListener('click', function() 
    // Open form logic.
  );

  function validateForm(form) 
    // Validation logic of all fields in form.
    // Return a true or false.
  

  function sendData(form) 
    // XHR logic, sends the data in the form.
  

  form.addEventListener('submit', function(event) 
    event.preventDefault();
    // Validate fields.
    if (validateForm(form)) 
      // If good, send. 
      sendData(form);
        
  );

);

【讨论】:

以上是关于如何验证表单数据,然后通过 AJAX 发送,然后在同一页面上显示提交的结果的主要内容,如果未能解决你的问题,请参考以下文章

总结

如何捕获表单值并通过电子邮件作为 ajax 请求发送?导轨

AJAXform表单验证

Python请求ajax表单身份验证问题

如何生成和验证 csrf 令牌

从表单收集数据,在对象中堆叠并使用 Vue 使用 AJAX 发送