如何验证表单数据,然后通过 AJAX 发送,然后在同一页面上显示提交的结果
how to validate form data, then send via AJAX, then show the submitted results on the same page
我正在建立一个简单的单页表单网站。我在验证与我的 AJAX 请求和 hiding/showing 提交的表单结果一起工作时遇到问题。这是我的问题:
- 当我单击
Begin
按钮打开注册表时,JS 验证已经触发,导致出现所有错误消息。我需要 "Begin" 按钮只打开表单而不触发 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+)*(\.\w{2,3})+$/;
const dateFormat = /^\d{4}[\-\/\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>
非常感谢对这三个问题的任何帮助!!!
- 初始错误的发生是因为您在 window 上验证了
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 请求和 hiding/showing 提交的表单结果一起工作时遇到问题。这是我的问题:
- 当我单击
Begin
按钮打开注册表时,JS 验证已经触发,导致出现所有错误消息。我需要 "Begin" 按钮只打开表单而不触发 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+)*(\.\w{2,3})+$/;
const dateFormat = /^\d{4}[\-\/\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>
非常感谢对这三个问题的任何帮助!!!
- 初始错误的发生是因为您在 window 上验证了
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);
}
});
});