I made a form for registration and use JavaScript for checking condition, but when I call that function, the alert message didn’t show for all but I call it alone, the dialog appeared.
This is my code for checking the condition of each field.
function validateForm() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("inputEmail4").value;
var password = document.getElementById("inputPassword4").value;
if (firstName === "" || lastName === "" || email === "" || password === "") {
alert("Please fill out all fields");
return false;
}
if ((firstName.length < 2 || firstName.length > 30) && firstName !== "") {
alert("First Name must be between 2 and 30 characters");
return false;
}
if (lastName.length < 2 || lastName.length > 30) {
alert("Last Name must be between 2 and 30 characters");
return false;
}
const emailPattern = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
if (!email.match(emailPattern)) {
alert("Invalid email address");
return false;
}
if (password.length < 2 || password.length > 30) {
alert("Password must be between 2 and 30 characters");
return false;
}
alert("Complete!");
}
<form class="row g-3" id="registrationForm" onsubmit="return validateForm();">
<div class="col-md-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" placeholder="First name">
</div>
<div class="col-md-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" placeholder="Last Name">
</div>
<div class="col-md-12">
<label for="inputEmail4" class="form-label">Email</label>
<input type="email" class="form-control" id="inputEmail4" placeholder="[email protected]">
</div>
<div class="col-md-12">
<label for="inputPassword4" class="form-label">Password</label>
<input type="password" class="form-control" id="inputPassword4">
</div>
<div class="d-grid gap-2 d-md-block">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-warning">Reset</button>
</div>
</form>



