views:

210

answers:

2

Hi all,

could you take a look at this http://jsbin.com/osolo/ please?

If you enter a letter in Min Age rather than a number then hit submit this validates using jquery validator using a regular expression in a custom validation method, this works but i'm now looking to make it a little more dynamic.

In the custom validation method the line

var data = $(element).metadata();

grabs meta data from the element being validated, what i would like to do is use the

data.validateOptions.regex

as the regex to test with (i can't see this being a problem), what i can see being a problem is that if the field doesn't validate, rather than using a message that is supplied when calling

jQuery.validator.addMethod(name, method, message)

i'd like to use

data.validateOptions.message

as the error message from within the custom method, can anyone point me in the right direction please?

Thanks

OneShot

A: 

What about creating a closure?

var data = {};
jQuery.validator.addMethod("perorgproperty", function(value, element) { 
    debugger; 
    //alert('testing perorgproperty'); 
    data = $(element).metadata(); 

    return this.optional(element) || /^\d+$/i.test(value); 
}, data.validateOptions.message);

As long as the function is evaluated before the message, wouldn't the message just be passed in by reference?

Alex Sexton
+1  A: 

I think Alex's answer won't work because strings are immutable in JS.

It's close though. Starting with Alex's code, if you create a closure containing the data object (or just a message string) and also a function returning the message, you can pass the function as the third argument to the addmethod call. Like so:

(function() {
    var data = {};
    var messager = function() {
        return data.validateOptions.message;
    };
    jQuery.validator.addMethod("perorgproperty", function(value, element) { 
        debugger; 
        //alert('testing perorgproperty'); 
        data = $(element).metadata();
        return this.optional(element) || /^\d+$/i.test(value); 
    }, messager);
})();
aweitzer