user3653474
user3653474

Reputation: 3852

Jquery Validator not working properly on a select dropdown

I am trying to validate a dropdown it is validating but its option value are also turning red when a validation error is shown.Like in the image color is also shown in Red but i don't want to change its color.

enter image description here

jQuery("#frm").validate({
            rules: {
                color: 'required',
                ...
            },

Upvotes: 0

Views: 2602

Answers (1)

Always Helping
Always Helping

Reputation: 14570

You need to use highlight method in your jQuery validate to ensure that the errorClass is not getting applied towards the select option as well.

Add this code in your jQuery validate after the messages

highlight: function(element, errorClass) {
   $(element).removeClass(errorClass); //prevent class to be added to selects
},

Live Working Demo:

$('#frm').validate({
  errorClass: "my_error",
  rules: {
    color: 'required'
  },
  messages: {
    someSelect: "Required *"
  },
  highlight: function(element, errorClass) {
    $(element).removeClass(errorClass); //prevent class to be added to selects
  },
  submitHandler: function(form) {
    //do something
  }
});
.my_error {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<form id="frm">
  <div class="form-group">
    <label for="exampleFormControlSelect1">Example select</label>
    <select class="form-control" name="color">
      <option selected disabled>Choose</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Upvotes: 2

Related Questions