I have an interesting question regarding validation and forms. I decided to use my own class, but I noticed that when the button is clicked, the border color does not display anymore.
I tried testing with CSS for invalid entries, and it worked. Now, I want the select border to turn red if the user presses the button and the entry is invalid. How can I achieve this? Here is my code:
var myForm = document.getElementsByClassName('needs-validation');
var btn = document.querySelector("[type='submit']")
btn.addEventListener("click", function() {
if (myForm.checkValidity()) {
('.select-user-role').setCustomValidity('')
} else {
alert("no");
}
});
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
.select-user-role:invalid {
border-color: red;
}
<div class="form-group row">
<label for="validationRole" class="col-form-label role">*Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<button type="submit" class="btn-primary submitbutton">Add</button>
This is how my website looks when there is an invalid entry: https://i.sstatic.net/YHFkt.png
I want the validation message and the border color to appear in red.