I'm working on a project and I am trying to add checks for the inputs on the form. I want it to only submit and move to the URL if the requirements are met. I'm using Javascript to check this. Currently, my code doesn't return any errors in the console but when I press submit even with blank inputs it submits and moves to the next page.
// Form Controls
const form = document.getElementById('form');
const username = document.getElementById('username');
const room = document.getElementById('room');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show Success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldName
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() input.id.slice(1);
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([username]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../static/style.css" rel="stylesheet">
<title>ChatR</title>
<script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>
<body>
<div >
<div >
<h1>MyApp</h1>
</div>
</div>
<div >
<form action="{{url_for('chat') }}" id="form" method="POST">
<div >
<input type="username" id="username" name="username" placeholder="Enter username">
<small>Error Message</small>
</div>
<div >
<input type="room" id="room" name="room" placeholder="Enter room">
<small>Error Message</small>
</div>
<button type="submit" >Start Chat</button>
</form>
</div>
</body>
</html>
CodePudding user response:
I made some changes to the code so it submits when it is successful.
The first thing is to have checkRequired
return true
or false
indicating if the validation was successful or not.
Second, check that value in the submit event listener and submit the form if it is valid.
// Check required fields, returning true/false if valid.
function checkRequired(inputArr) {
var success = true; // <= assume success
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
success = false; // <= if anything fails, the not successful
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
return success; // return value indicating success
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
// submit only if validation is successful
if(checkRequired([username, room])){
form.submit();
}
});
By the way, you might want to add room
to the array of inputs being validated.
CodePudding user response:
The problem here is Because the element is not found in the DOM while the script is running with this it will run after dom gets loaded. So solution for this is to add a this line on top of scripts.js
document.addEventListener("DOMContentLoaded", () => {
//whole scripts.js in this section
//ends with this
})
with this it will loads and check if DOM is loaded or not and after that your script will work