Reputation: 2245
I have in my html something like this:
<input type="text" data-validators="length(5,25);notNull();links(1);" />
Functions: length, notNull and links are in my Validation class. I am getting these functions with jQuery
$(this).find('[data-validation]').each ->
validatorsString = $(this).attr "data-validation"
validatorsArray = validatorsString.split ";"
validatorsObject = new Validation($(this).val())
for v in validatorsArray
if typeof validatorsObject[v] == "function"
validatorsObject[v]
This works fine when I dont use parameters (arg1, arg2) but now I want to use parameters. How to check if these functions exists in class and execute it with paramters (with no limits, it can be 1, 5, 10 params)
Upvotes: 0
Views: 382
Reputation: 1771
Since you can't dynamically call functions with arguments as strings (unless you use eval
), the best method to achieve the functionality you want you'll have to parse your data-validation
information:
given this string: validatorsString="length(5,25);notNull();links(1);"
, you could parse it into function names and arguments using a regular expression:
validatorsString.replace(/([\w_$]+)\(([\w_$,]+)\)/g, (all, fn, args) ->
args = args.split ',' if args
if typeof validatorsObject[fn] is 'function'
validatorsObject[fn].apply validatorsObject, args
)
Upvotes: 3