Hello, I’m currently practicing form validation with javascript. For some reason, I’m getting an error for the password input being empty, even though it isn’t. If anyone could take a look and point me in the right direction that would be great!
https://intro-component-form-validation.netlify.com/
Here’s the code:
let fname = document.getElementById("fname").value
let fnameInput = document.getElementById("fname")
let fnameErrorMsg = document.getElementById('fname-error')
let lname = document.getElementById('lname').value
let lnameInput = document.getElementById('lname')
let lnameErrorMsg = document.getElementById('lname-error')
let email = document.getElementById('email').value
let emailInput = document.getElementById('email')
let emailErrorMsg = document.getElementById('email-error')
let pass = document.getElementById('pass').value
let passInput = document.getElementById('pass')
let passErrorMsg = document.getElementById('pass-error')
validateForm = () => {
event.preventDefault()
if (fname == "" || fname == null || fname.length == 0) {
fnameErrorMsg.style.display = "flex";
fnameInput.style.border = "1px solid hsl(0, 100%, 74%)";
} else {
null
}
if (lname == "" || lname == null || lname.length == 0) {
lnameErrorMsg.style.display = "flex"
lnameInput.style.border = "1px solid hsl(0, 100%, 74%)";
} else {
null
}
if (email == '' || email == null || email.length == 0) {
emailErrorMsg.style.display = "flex"
emailInput.style.border = "1px solid hsl(0, 100%, 74%)";
} else {
null
}
if (pass == '' || pass == null || pass.length == 0) {
passErrorMsg.style.display = "flex"
passInput.style.border = "1px solid hsl(0, 100%, 74%)";
} else {
null
}
}
<form id="form" action="submit">
<!-- Form input 1 -->
<label for="fname" class="label">First Name</label>
<input type="text" id="fname" placeholder="First Name">
<p id="fname-error" class="error">First Name cannot be empty</p>
<!-- Form input 2 -->
<label for="lname" class="label">lastName Name</label>
<input type="text" id="lname" placeholder="Last Name">
<p id="lname-error" class="error">Last Name cannot be empty</p>
<!-- Form input 3 -->
<label for="email" class="label">Email</label>
<input type="email" id="email" placeholder="Email Address">
<p id="email-error" class="error">Looks like this is not an email</p>
<!-- Form input 4 -->
<label for="pass" class="label">password</label>
<input type="password" minlength="4" id="pass" placeholder="Password">
<p id="pass-error" class="error">password cannot be empty</p>
<button type="submit" onClick="validateForm()" class="submit">Claim your free trial </button>
</form>
EDIT: Any general feedback about code quality is also appreciated!