Page 1 of 1

[JQUERY] More sophisticated validating rules

Posted: Sun Mar 21, 2010 3:32 am
by filip11
Hi,

this is my firt post on this forum. I am sorry about my english, which is poor, but I dont speak english every day.

I am using a validating form plugin for jquery and I have a quetion about it. Let this function will be an ex.:

Code: Select all

$('#form_id').validate(){
      rules: {
      e:{
      required: true,
      email: true
      }
      }
      });
'e' is the name atribute of one form element, but can I choose more elements using jquery (css) rules like this: input[name*=e] or how can I do something similar?

thx for your answers in advance and once again sorry about my english.

Re: [JQUERY] More sophisticated validating rules

Posted: Mon Mar 22, 2010 6:32 am
by kaszu
I haven't tested following code, hopefully it works:

Code: Select all

//Create new plugin on top of .validate
jQuery.fn.validateExtended = function (options) {
    var form = $(this);
 
    //Create options copy without rules
    var newoptions = $.extend({}, options);
    newoptions.rules = {};
 
    //Make sure rules exists
    if ('rules' in options) {
        
        //Go through all rules
        for(var i in options.rules) {
            //Find all elements (input, select, textarea, etc.) which name is "like" given
            form.find('*[name*=' + i + ']').each(function () {
                //Add new rule for each input
                newoptions.rules[$(this).attr('name')] = options.rules[i];
            });
        }
        
    }
 
    return form.validate(newoptions);
};
 
//Example:
$('#form_id').validateExtended({
    rules: {
        e:{
            required: true,
            email: true
        }
    }
});
//for inputs with names "e1" and "e2" should work same as
$('#form_id').validate({
    rules: {
        e1:{
            required: true,
            email: true
        },
        e2:{
            required: true,
            email: true
        }
    }
});