I've see a lot of solution and questions similar to this but none of them helped me out
here is a simple html form with JavaScript validation
log error message on key up when the value of input fields are less than required length (less than 5)
log error message on submit when input fields are empty (first Name and last Name)
problem is when I click submit button form is submitted regardless of errors
I have tried preventDefault() and return false but none of them worked out
how can I improve the code to make them work correctly? for both key up and submit
let fname = document.getElementById('fname');
let lname = document.getElementById('lname');
form = document.querySelector('#myForm');
function checkFirstName() {
let valid = true;
if (fname.value.length < 5) {
console.log('first name must be greater than 5');
valid = false;
}
}
function checkLastName() {
let valid = true;
if (lname.value.length < 5) {
console.log('last name must be greater than 5');
valid = false;
}
}
form.addEventListener('input', function(e) {
switch (e.target.id) {
case 'fname':
checkFirstName();
break;
case 'lname':
checkLastName();
break;
}
});
form.addEventListener('submit', function(e) {
let isFormField = true;
if (fname.value === '') {
console.log('first name is required')
isFormField = false;
}
if (lname.value === '') {
console.log('last name is required')
isFormField = false;
}
if (!isFormField) {
e.preventDefault();
return
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="fname" name="fname"></br>
<small class="small" id="small"></small>
</div>
<div>
<input type="text" class="form-control" id="lname" name="lname"></br>
<small class="small" id="small"></small>
</div>
<button type="submit" name="send">submit</button>
</form>
<br />and not</br>checkFirstNameandcheckLastNameoninputevent. If user submit form then you are not validating the inputs.