How to properly style custom bootstrap form validation

181 views Asked by At

I have created a custom validation check for bootstrap form validator (it's the else part below) :

Array.prototype.slice.call(forms).forEach(function (form) {
    form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
        }
        else if (myConditionIsNotMet()) {
            form.querySelector("#myInputField").classList.add('is-invalid');
            event.preventDefault()
            event.stopPropagation()
        }
        form.classList.add('was-validated')
    }, false)
})

The targeted input field already has a "required" attribute that works fine.

Using the above code, I have managed to make the validation error message appear and stop the form submission, but the outline of the field is green instead of red.

enter image description here

It seems my element ends up with both the is-valid and is-invalid classes due to the "required" validation.

enter image description here

I read in another post that there's an updateStatus function that can set a field as invalid. It seems that's what I need, but I haven't figured out how to access it via my form element.

Any help would be appreciated, I'm a noob when it comes to javascript :\

1

There are 1 answers

0
Yiorgos On

I'm pretty sure this is NOT the optimal solution, but I managed to get what I wanted with this:

Array.prototype.slice.call(forms).forEach(function (form) {
    form.addEventListener('submit', function (event) {
        if (myConditionIsNotMet()) {
            form.querySelector("#myInputField").setCustomValidity("Oops!");
        }
        else {
            form.querySelector("#myInputField").setCustomValidity("");
        }
        if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
        }
        form.classList.add('was-validated')
    }, false)
})