Измените идентификаторы поля формы так, чтобы они совпадали с именем и префиксом div ошибки, чтобы избежать многих ошибок.
Я бы передал (это) в обработчики, тогда я мог бы получить значение и идентификатор из этого
На кнопке нет onsubmit. Это указано в форме.
Я рекомендую вам сделать следующее:
document.querySelector("[name=InviteForm]")
.addEventListener("submit",validateForm)
используя
function validateForm(e) {
.....
if (fnameErr || lnameErr || emailErr) { e.preventDefault() }
}
и изменить отправку на
<input class="button submit" type="submit" value="Get Invited">
Я добавил сюда свои предложения:
function validateNameField(input) {
const inputId = input.id
const errDivId = inputId+"Err";
var inputValue = input.value;
if (inputValue == "") {
printError(errDivId, "What's your first name?");
document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)
} else {
var regex = /^[a-zA-Z]{2,}$/;
if (regex.test(inputValue) === false) {
printError(errDivId, "Valid names don't contain spaces"); //function is in formvalidation.js file
} else {
printError(errDivId, "");
nameErr = false;
document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
}
}
}
// Validate email address
function validateEmailField(input) {
const inputId = input.id
const errDivId = inputId+"Err";
var inputValue = input.value;
if (inputValue == "") {
printError(errDivId, "What's your email?");
document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)
} else {
// Regular expression for basic email validation
var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
if (regex.test(inputValue) === false) {
printError(errDivId, "Valid emails don't contain any typos");
} else {
printError(errDivId, "");
emailErr = false;
document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
}
}
}
// JavaScript Document
// Defining a function to display error message
function printError(elemId, hintMsg) {
console.log(elemId)
document.getElementById(elemId).innerHTML = hintMsg;
document.getElementById(elemId).style.display = "block"; //could I use jQuery show()?
}
// Defining a function to validate form
function validateForm(e) {
// Defining error variables with a default value. True means there are errors and form won't be submitted.
var fnameErr = lnameErr = emailErr = true;
// Validate fname
if (typeof document.InviteForm.fname !== "undefined") {
var fname = document.InviteForm.fname.value;
if (fname == "") {
printError("fnameErr", "What's your first name?");
} else {
var regex = /^[a-zA-Z]{2,}$/;
if (regex.test(fname) === false) {
printError("fnameErr", "Valid names don't contain spaces");
} else {
printError("fnameErr", "");
fnameErr = false;
document.getElementById("fnameErr").style.display = "none"; //could I use jQuery hide()?
}
}
}
// Validate fname
if (typeof document.InviteForm.lname !== "undefined") {
var lname = document.InviteForm.lname.value;
if (lname == "") {
printError("lnameErr", "What's your last name?");
} else {
var regex = /^[a-zA-Z]{2,}$/;
if (regex.test(lname) === false) {
printError("lnameErr", "Valid names don't contain spaces");
} else {
printError("lnameErr", "");
lnameErr = false;
document.getElementById("lnameErr").style.display = "none"; //could I use jQuery hide()?
}
}
}
// Validate email address
if (typeof document.InviteForm.email !== "undefined") {
var email = document.InviteForm.email.value;
if (email == "") {
printError("emailErr", "What's your email?");
} else {
// Regular expression for basic email validation
var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
if (regex.test(email) === false) {
printError("emailErr", "Valid emails don't contain any typos");
} else {
printError("emailErr", "");
emailErr = false;
document.getElementById("emailErr").style.display = "none"; //could I use jQuery hide()?
}
}
}
// Prevent the form from being submitted if there are any errors
if (fnameErr || lnameErr || emailErr) {
e.preventDefault(e);
} else {
// Creating a string from input data for preview
var dataPreview = fname + lname + email;
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};
window.addEventListener("load",function() {
document.querySelector("[name=InviteForm]")
.addEventListener("submit",validateForm)
})
/* ----------> FORM <---------- */
.inviteformcontainer {
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
position: relative;
height: calc(100vh - 6em);
}
.inviteform {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
width: 50vw;
grid-column-gap: 2em;
}
.firstname {
grid-column: 1/3;
}
.lastname {
grid-column: 3/5;
}
.inputcontainer {}
.error {
font-family: inherit;
border: 1px solid #f47b22;
background: #fafafa;
color: #f47b22;
font-family: sans-serif;
font-size: .75em;
padding: 1em 1em;
height: 3em;
box-sizing: border-box;
width: 100%;
margin-bottom: 1em;
display: none;
}
.email {
grid-row: 2/3;
grid-column: 1/5;
}
.submit {
grid-row: 3/4;
grid-column: 2/4;
justify-self: center;
}
.button {
font-family: futura;
font-size: 1em;
font-weight: 700;
letter-spacing: .26em;
font-style: normal;
text-transform: uppercase;
color: white;
border: 0;
background-color: #f47b22;
border-color: #f47b22;
border-style: solid;
padding: 2em 3em;
text-align: center;
text-decoration: none;
cursor: pointer;
-webkit-appearance: none;
-moz-appearance: none;
place-self: center;
}
.button:hover {
background-color: #f48f22;
border-color: #f48f22;
border-style: solid;
border: 0;
}
input[type=text],
input[type=number],
input[type=email] {
font-family: inherit;
border: 1px solid #ccc;
background: #fafafa;
color: #000;
font-family: sans-serif;
font-size: 1em;
padding: 2em 1em;
height: 3em;
box-sizing: border-box;
width: 100%;
}
input:invalid {
box-shadow: none;
}
<form name="InviteForm" class="inviteform" method="post">
<div class="firstname inputcontainer">
<input type="text" id="fname" name="fname" placeholder="First Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this)">
<div class="error" id="fnameErr"></div>
</div>
<div class="lastname inputcontainer">
<input type="text" id="lname" name="lname" placeholder="Last Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this)">
<div class="error" id="lnameErr"></div>
</div>
<div class="email inputcontainer">
<input type="email" id="email" name="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}" onfocusout="validateEmailField(this)">
<div class="error" id="emailErr"></div>
</div>
<input class="button submit" type="submit" value="Get Invited"/>
</form>