I’ve been assigned a task to make a sign-up page for a hypothetical training business.
I’m currently creating the form validation for the first name input, which checks whether the field is empty, equal to the placeholder, has any numbers or special characters. However, my code is not responding when I click my button element (not input type=submit).
The expected result was the font colour to change to pink and the innerText to display “Please enter a valid first name”.
I’ve attempted calling both the form form.addEventListener("submit", newCustomer);
and the button tn.addEventListener("submit", newCustomer);
in my javascript, but nothing happens.
div class="form-container">
<form action="" id="form">
<div class="form-top">
<div class="title">
<label for="firstname" class="firstname">First Name:</label>
<label for="lastname" class="lastname">Last Name:</label>
<label for="email address" class="email-address">Email:</label>
<label for="card details " class="card-details"> Card:</label>
</div>
<div class="textbox">
<input type="text" placeholder="Enter Your Firstname" id="f-name">
<input type="text" placeholder="Enter Your Last Name" id="l-name">
<input type="text" placeholder="Enter Your Email" id="email">
<input type="text" placeholder="Enter a Proxy Credit Card Number" id="card">
</div>
</div>
<div class="button-container"><button id="btn" type="submit">Submit</button></div>
</form>
<script>
var fname = document.getElementById("f-name");
var lname = document.getElementById("l-name");
var email = document.getElementById("email");
var card = document.getElementById("card");
const btn = document.getElementById("btn");
const form = document.getElementById("form");
var Customers = [];
function newCustomer(event, firstname, lastname, emailAddress, cardNum) {
event.preventDefault();
firstname = fname;
lastname = lname;
emailAddress = email;
cardNum = card;
if (firstname === "" || firstname.placeholder === "Enter Your Firstname") {
firstname.innerText = "Please enter a valid first name";
firstname.style.color = "rgb(231,0,100)";
} else {
var specialChars = /[!@#$%^&*(),.?":{}|<>]/g;
for (let i = 0; i < firstname.value.length - 1; i++) {
if (!isNaN(firstname[i])) {
firstname.placeholder.style.color = "rgb(231,0,100)";
firstname.placeholder.innerText = "Please enter a valid first name";
} else if (specialChars.test(firstname[i]) == true) {
firstname.style.color = "rgb(231,0,100)";
firstname.innerText = "Please enter a valid first name";
} else {
firstname.style.color = "rgb(137,200,46)";
form.reset();
}
}
}
}
btn.addEventListener("submit", newCustomer);
</script>
</div>