Nevermore
Nevermore

Reputation: 882

Why does this jquery validate rule not work?

I have created a jquery validate rule for following select-box and it is not working. Here is what I have done;

<select id="qual">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

My rule is as follows -

  $.validator.addMethod("qual", function(value, element, arg){

    return arg != value;
   }, "Please select a qualification.");

 $("#profile-form").validate({
    rules: {
     eduQualification:{
        qual: ""
      },
   }
)};

The problem is that it does not flash error message even when I select "Choose ..." from select box.

And while submitting the form; it gets submitted even if the jquery validate returned some error or not. I have called the preventDefault(); however, it seems to fail as well..

$(document).on('click', 'form button[type=submit]', function(e) {
            var isValid = $(e.target).parents('profile-form').isValid();

            if(!isValid) {
              e.preventDefault(); //prevent the default action
            } else{

            }
        });

Upvotes: 1

Views: 72

Answers (1)

Sparky
Sparky

Reputation: 98758

  1. What is the qual rule supposed to accomplish? Typically, a select only needs the required rule since the user can only make a selection, and has no control over the format of the selected value.

  2. Your rules object is targeting the eduQualification element, but you have no element with this name.

  3. Your closing braces for .validate() are backwards. Should be }); ... as in .validate({...});

Your select must contain a name attribute or the plugin will not work at all; and it must be name="eduQualification" for the way you've declared it within the rules object.

$("#profile-form").validate({
    rules: {
        eduQualification: { // <- this is the NAME
            qual: ""        // <- this is the METHOD
            ....

HTML: <select name="eduQualification" id="qual">.....


To simply change the message, use the messages object as follows...

<select name="foo">
    <option value="">Choose...</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

jQuery:

$(document).ready(function() {

    $("#myform").validate({
        rules: {
            foo: {
                required: true
            }
        },
        messages: {
            foo: {
                required: "Please select a qualification."
            }

        }
    });

});

Working DEMO: http://jsfiddle.net/773Lozwz/

Upvotes: 1

Related Questions