I am trying to validate form so when it is validated, i should see the message from the alert and the fields become clear. Though on submitting in below code 'isfformValid==true' is not getting executed after i fill all info properly in the form. Any idea.
const form = document.getElementById('create-account-form');
const usernameInput = document.getElementById('username');
form.addEventListener('submit', (event) => {
validateForm();
if (isFormValid == true) {
alert("form submitted"); // this is not called and it goes to prevent default
form.submit();
} else {
event.preventDefault();
}
});
function isFormValid() {
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container) => {
if (container.classList.contains('error')) {
result = false;
}
});
return result;
}
function validateForm() {
//USERNAME
if (usernameInput.value.trim() == '') {
setError(usernameInput, 'Name can not be empty');
} else if (usernameInput.value.trim().length < 5 || usernameInput.value.trim().length > 15) {
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
} else {
setSuccess(usernameInput);
}
<body>
<form id="create-account-form" action="" method="">
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username">
<p>Error Message</p>
</div>
<!-- EMAIL -->
<div class="input-group">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Email" name="email">
<p>Error Message</p>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<script src="app.js"></script>
</body>