Browse files

Make jQuery validations adapter work nice with functions as arguments

  • Loading branch information...
1 parent ca278c4 commit e6904d149977c991898d416cfd7b5c29f4ada0ba @manuelmeurer manuelmeurer committed Oct 5, 2009
View
15 lib/live_validations/adapters/jquery_validations.rb
@@ -98,7 +98,7 @@ class JqueryValidations < LiveValidations::AdapterBase
%{
#{custom_rules(a)}
- $('##{dom_id}').validate(#{validator_options.to_json})
+ $('##{dom_id}').validate(#{to_json_with_function_awareness(validator_options)})
}
end
@@ -114,6 +114,19 @@ def self.add_custom_rule(v, attribute, identifier, validation, message)
def self.custom_rules(a)
a[:declarations].join("\n")
end
+
+ def self.to_json_with_function_awareness(validator_options)
+ functions = {}
+ function_strings = validator_options.select { |k, v| v.is_a?(String) && v.starts_with?('function') }
+ function_strings.each_with_index do |function_string, i|
+ function_key = "%function_#{i + 1}%"
+ functions[function_key] = function_string.last
+ validator_options[function_string.first] = function_key
+ end
+ functions.inject(validator_options.to_json) do |json, function|
+ json.gsub(/"#{function.first}"/i, function.last)
+ end
+ end
end
end
end
View
8 test/jquery_validations_controller_output_test.rb
@@ -42,6 +42,14 @@ def test_json_output
assert rendered_view.include?(expected_json.to_json)
end
+ def test_validator_options_with_function
+ Post.validates_presence_of :title
+ LiveValidations.use LiveValidations::Adapters::JqueryValidations, :validator_settings => {"errorPlacement" => "function(error, element) { error.appendTo(element.prev('label')); }"}
+
+ render
+
+ assert rendered_view.include?(%["errorPlacement":function(error, element) { error.appendTo(element.prev('label')); }])
+ end
def test_validator_options
Post.validates_presence_of :title

0 comments on commit e6904d1

Please sign in to comment.