Reputation: 2245
I have a function:
validatorsString.replace(/([\w_$]+)\(([\w_$,]+)\)/g, (all, fn, args) ->
args = args.split ','
if typeof validatorsObject[fn] is 'function'
res = validatorsObject[fn].apply validatorsObject, args
if res == false
formBox.addError obj, "Pole musi byc takie"
return false
#obj.css "background-color", "red"
)
I want to do something if everything is good. Above function is calling validators (1,3,10) and I want to send ajax if every validator returned true. How to do this ?
Upvotes: 1
Views: 94
Reputation: 5354
I think you will keep it cleaner in the future, if you keep the logic of running the validators and updating the view in separate functions. Then, you can write it like this:
isValid = (validationString) ->
re = /([\w_$]+)\(([\w_$,]+)\)/g
while match = re.exec(validationString)
[fn, args] = [match[1], match[2].split(',')]
if _(validatorsObject[fn]).isFunction() and not validatorsObject[fn].apply validatorsObject, args
return false
true
unless isValid(validationString)
formBox.addError obj, "Pole musi byc takie"
I've used underscore.js for checking the type of the validator, because I believe that typeof
check like the one in your code fails on Android 2.3 stock browser. Some food for thought.
Upvotes: 2
Reputation: 19040
You need to keep a "global state"
isValid = true
validatorsString.replace(/([\w_$]+)\(([\w_$,]+)\)/g, (all, fn, args) ->
return unless isValid # short-circuit if we detected an error already
args = args.split ','
if typeof validatorsObject[fn] is 'function'
res = validatorsObject[fn].apply validatorsObject, args
isValid = false unless res
unless isValid
formBox.addError obj, "Pole musi byc takie"
#obj.css "background-color", "red"
return false
$.post "stuff"
Upvotes: 1