bootstrap-validate for select inputs for bootstrap 4

1.8k views Asked by At

I have using the bootstrap-validate for bootstrap 4 located here:

https://bootstrap-validate.js.org/installation.html

I am trying to get it to validate a select input which I have like this:

    <div class="form-group">
        <label for="numberOfBedrooms">Number of Bedrooms<span>*</span></label>
        <select class="form-control" name="numberOfBedrooms" id="numberOfBedrooms" required>
            <option value="">Please select</option>
            <option value="1">1 Bedroom</option>
            <option value="2">2 Bedrooms</option>
            <option value="3">3 Bedrooms</option>
            <option value="4">4 Bedrooms</option>
            <option value="5">5+ Bedrooms</option>
        </select>
    </div>

My script does this:

bootstrapValidate('#numberOfBedrooms', 'required:Please select one option');

But it doesn't appear to validate. There is no class assigned to the select input field or the form-group. Does anyone know why this isn't working?

1

There are 1 answers

0
Slimelord On

I would check that you are correctly bringing in the library to start with. When I brought in your code to a JSFiddle and added this code to it:

bootstrapValidate('#numberOfBedrooms', 'required:Please select one option', function (isValid) {
   if (isValid) {
       alert('Element is valid');
   } else {
       alert('Element is invalid');
   }
});

It correctly would alert me when I have selected a valid/invalid input. However, it should be noted that when looking at the console the following error would appear

Assertion failed: Input argument is not an HTMLInputElement

So it's possible that it's not treating the select as a proper input element and reading the length of that select correctly. Also, where exactly in your javascript are you calling the validate method? I assume you have a button that submits and in the onclick of that button?