views:

248

answers:

2

Hi there, i am using the Jquery validation plugin, sourced from here.

It is function well for required fields, email etc, however I would like to set up some specific validation rules for certain form fields. For example, I have a select form field which contains the following options...

    <select name="salutation" id="salutation" class="conditional">
    <option value="0">--- Please Select ---</option>
            <option value="1">--- MR ---</option>
            <option value="2">--- MRS ---</option>
    </select>

I would then like to use the validation plugin to display a message if a salutation has not been selected..I.E

    $("#userForm").validate({
   // Validate Fields On Blur   
      onfocusout: function(element){
      this.element(element);
   },
     // Set Specific Rules for Validation
     rules:{
     salutation: {
        NEQ:0                   
             }
    },
    messages:{
    salutation: {
    NEQ: "please select a salutation"               
     }
    }
   });

Wondering if anyone had any ideas on how to customize the plugin to allow such things. Many thanks

A: 

Leave the value empty for the "Please select" option and make the select field required by assigning it the class required. That should be enough to ensure that one of the other options is chosen. Note that it will have the default message: "This field is required." instead of your custom message, but you could adjust that as well.

<select name="salutation" id="salutation" class="required"> 
    <option value="">--- Please Select ---</option> 
    <option value="1">--- MR ---</option> 
    <option value="2">--- MRS ---</option> 
</select> 

$("#userForm").validate({ 
  // Validate Fields On Blur    
  onfocusout: function(element){ 
                  this.element(element); 
              }
});
tvanfosson
Hi there, thanks for your answer. It doesnt appear to be working unfortunately, not sure why
namtax
@namtax: Sorry -- my example omitted the value instead of providing an empty value. When the value is omitted it takes on the text as the value. Providing an empty value allows the required class to work properly with the plugin. I've updated the example. I prefer using required because that's the sense of the selection -- you require a value. Range or even min would work, but it doesn't really have the same semantics in this case "value is out of range" or "value must be at least 1"...
tvanfosson
+1  A: 

you could use range in this case

range: [1, 2]
Natrium
Worked like a beauty...thanks for your assistance
namtax
note: this is a good workaround, but actually this doesn't solve the coreproblem: how to exclude specific values or how to validate against a certain set of values?
Natrium