4

I have 2 forms, namely (ids mentioned) 'add_product' and 'edit_product'

Now I am using jQuery validation plug-in, both the forms have same validation (similar to mentioned in following example)

jQuery("#add_product").validate({
    rules: {
        name:"required",
        price:"number"
    },
    messages: {
        name:"Please enter Plan Name",
        price:"Enter a valid number"
    }

});

and

jQuery("#edit_product").validate({
    rules: {
        name:"required",
        price:"number"
    },
    messages: {
        name:"Please enter Plan Name",
        price:"Enter a valid number"
    }

});

I want to combine them into 1 rule/function, how can I achieve this?

Thanks

1 Answer 1

7

Store the options in a variable and reuse it.

var vProduct = {
    rules: {
        name:"required",
        price:"number"
    },
    messages: {
        name:"Please enter Plan Name",
        price:"Enter a valid number"
    }
};

jQuery("#add_product").validate(vProduct);
jQuery("#edit_product").validate(vProduct);

Unfortunately you can't simply use jQuery("#add_product, #edit_product").validate({...}) because the plugin doesn't handle more than one element being selected.

Sign up to request clarification or add additional context in comments.

2 Comments

I need to ask you something, generally for jQuery '$' is used, why here 'jQuery' is used, is it valid?
@I-M-JM, 'jQuery' is used when there may be a conflict with another library that uses '$', e.g. Prototype or Mootools. It's completely valid, but is just more to type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.