Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate: Not default value

I have a category dropdown selection element in my form. The form is validated with jQuery as follows:

    $('#myForm').validate({
    rules: {
        text: {
              required: true
        },
        category: {
            required: true
        }
    },
    messages: {
        text: {
            required: "Text required"
        },
        category: {
            required: "Category required"
        }
    }

When loading the page, the default value of category is: '---' (without quotes). When I submit the form, the validation says eveything is ok, because '---' is not nothing. How can I get it to stop submitting when '---' is used as category? The other categories are something like this: Category1. One of the possibilities have to be choosen and I can't change the dropdown selection thing.

Thanks!!

like image 906
koenHuybrechts Avatar asked Dec 13 '22 19:12

koenHuybrechts


1 Answers

You could add a custom rule, like this:

jQuery.validator.addMethod("notEqual", function(value, element, param) {
  return this.optional(element) || value !== param;
}, "Please choose a value!");

Then use that rule in your rules, like this:

    category: {
        required: true,
        notEqual: "---"
    }

You can test it out here.

like image 66
Nick Craver Avatar answered Jan 01 '23 19:01

Nick Craver