Reputation: 11
I am trying to add error message handling in Javascript but am having trouble. If a user inputs a state that is not two characters in length, I am trying to have it output an error message. I also am including my renderBarChart function too if that helps.
js
stateSubmitButton.addEventListener("click", function(event) {
event.preventDefault();
state = stateUserInput.value.toUpperCase();
let stateFeedbackElem = document.querySelector("#stateFeedback");
if (state.length == 2) {
stateUserInput.setCustomValidity("");
stateFeedbackElem.textContent = "";
renderBarChart(state);
state = "";
} else {
stateUserInput.setCustomValidity("Please enter a two letter abbreviated state.");
stateFeedbackElem.textContent = "Please enter a two letter abbreviated state.";
state = "";
}
})
html
<form class="form" novalidate>
<label for="state-input">State:</label>
<input name="state" type="text" id="state-input" placeholder="(i.e. WA)">
<button type="submit" id="state-submit" class="btn btn-dark btn-lg ml-2">Submit</button>
<div id="stateFeedback" class="invalid-feedback"></div>
</form>
Upvotes: 0
Views: 179
Reputation: 2058
I noticed a couple of problems.
You have set novalidate
on your form, which means .setCustomValidity()
error will not be shown as validation will not be performed.
If the
novalidate
attribute is set on the<form>
element, interactive validation of the constraints doesn't happen.
If stateUserInput
is the #state-input
input, .textContent
should work, and the text should be set. But it is probably not shown as the invalid-feedback
class has CSS property display: none;
. You need to add a d-block
class or use invalid-feedback
element as shown in Bootstrap examples.
And just a note, prefer to add an event listener on the form and listen for the SubmitEvent instead of the click
event on the submit button.
Upvotes: 1