I am trying to implement a custom validation for the form, however only one of my inputs actually work. What's more, the function, for some reason, doesn't recognize if there is any text or not in the input field.
Here is the code of one of the inputs of the form:
<form class="formWrapper">
<div class="inputWrapper">
<input
class="formInput"
required
type="text"
name="first-name"
id="first-name"
placeholder="First Name"
/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div class="errorMessage hidden">
<i>First name cannot be empty</i>
</div>
</div>
<div class="inputWrapper">
<input
class="formInput"
required
type="text"
name="last-name"
id="last-name"
placeholder="Last Name"
/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div class="errorMessage hidden">
<i>Last Name cannot be empty</i>
</div>
</div>
<div class="inputWrapper">
<input
class="formInput"
required
type="text"
name="Email"
id="Email"
placeholder="Email Address"
/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div id="emailError" class="errorMessage hidden">
<i>Email cannot be empty</i>
</div>
</div>
<div class="inputWrapper">
<input
class="formInput"
required
type="text"
name="Password"
id="Password"
placeholder="Password"
/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div class="errorMessage hidden">
<i>Password cannot be empty</i>
</div>
</div>
<button type="submit" class="claimButton">
Claim Your Free Trial
</button>
<div class="termsSection">
By clicking the button, you are agreeing to our
<b class="redBold">Terms and Services</b>.
</div>
</form>
And here is the JavaScript code, that I have written.
"use strict";
const formInput = document.querySelectorAll(`.formInput`);
const errorImg = document.querySelector(`.errorImg`);
const errorMessage = document.querySelector(`.errorMessage`);
const submitButton = document.querySelector(`.claimButton`);
const firstName = document.querySelector(`#first-name`);
const lastName = document.querySelector(`#last-name`);
const email = document.querySelector(`#Email`);
const password = document.querySelector(`#Password`);
const inputFields = [
{ inputName: firstName },
{
inputName: lastName,
},
{
inputName: email,
},
{
inputName: password,
},
];
const errorOccured = function (i) {
errorMessage.classList.remove(`hidden`);
errorImg.classList.remove(`hidden`);
formInput.classList.add(`errorState`);
};
for (let i = 0; i < inputFields.length; i++) {
inputFields[i].inputName.addEventListener("invalid", function (e) {
e.preventDefault();
});
}
submitButton.addEventListener("click", function () {
for (let i = 0; i < inputFields.length; i++) {
if (inputFields[i].inputName.value === "") {
errorOccured(i);
}
}
});
The form itself looks like this:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…