0

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)

1 Answer 1

3

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
)
Sign up to request clarification or add additional context in comments.

Comments

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.