Added required validator action dependant - feature #286

This commit is contained in:
Carlos Segura 2011-08-10 16:00:12 +02:00
parent b81801b08e
commit 8f92f0e88a
3 changed files with 25 additions and 3 deletions

View File

@ -67,7 +67,7 @@ module SimpleForm
options[:required]
elsif has_validators?
(attribute_validators + reflection_validators).any? do |v|
v.kind == :presence && !conditional_validators?(v)
v.kind == :presence && !conditional_validators?(v) && action_validators?(v)
end
else
attribute_required_by_default?
@ -96,9 +96,13 @@ module SimpleForm
end
def conditional_validators?(validator)
validator.options.include?(:if) || validator.options.include?(:unless)
validator.options.include?(:if) || validator.options.include?(:unless)
end
def action_validators?(validator)
validator.options.include?(:on) ? validator.options[:on] == ACTIONS.key(template.controller.action_name.to_sym) : true
end
def attribute_required_by_default?
SimpleForm.required_by_default
end

View File

@ -345,6 +345,22 @@ class FormBuilderTest < ActionView::TestCase
assert_select 'input.optional#validating_user_age'
end
test 'builder input should be required when validation is on create' do
@controller.action_name = "new"
with_form_for @validating_user, :action
assert_select 'input.required'
assert_select 'input[required]'
assert_select 'input.required[required]#validating_user_action'
end
test 'builder input should not be required when validation is on other action' do
@controller.action_name = "edit"
with_form_for @validating_user, :action
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#validating_user_action'
end
test 'builder input should not be required when ActiveModel::Validations is included and unless option is present' do
with_form_for @validating_user, :amount
assert_no_select 'input.required'

View File

@ -42,7 +42,7 @@ class User
:description, :created_at, :updated_at, :credit_limit, :password, :url,
:delivery_time, :born_at, :special_company_id, :country, :tags, :tag_ids,
:avatar, :home_picture, :email, :status, :residence_country, :phone_number,
:post_count, :lock_version, :amount, :attempts
:post_count, :lock_version, :amount, :attempts, :action
def initialize(options={})
options.each do |key, value|
@ -79,6 +79,7 @@ class User
when :home_picture then :string
when :amount then :integer
when :attempts then :integer
when :action then :string
end
Column.new(attribute, column_type, limit)
end
@ -129,6 +130,7 @@ class ValidatingUser < User
validates :company, :presence => true
validates :age, :presence => true, :if => Proc.new { |user| user.name }
validates :amount, :presence => true, :unless => Proc.new { |user| user.age }
validates :action, :presence => true, :on => :create
validates_numericality_of :age,
:greater_than_or_equal_to => 18,
:less_than_or_equal_to => 99,