Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom validation contexts in required #1759

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

phylor
Copy link

@phylor phylor commented Feb 2, 2022

This PR proposes to support custom validation contexts to determine whether a field is required or not.

Current Behavior

Given the model:

class User
  validates :name, presence: true
  validates :avatar, presence: true, on: :with_picture
end

The following currently renders both name and avatar as required:

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.input :avatar %>
<% end %>

This does not correspond to the behavior of @user.save, which does not require avatar.

Proposed Solution

This PR proposes a new option context on inputs. Its value is used to determine whether the input is required or not.

The above example would only mark name as required. The following example marks both name and avatar as required.

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.input :avatar, context: :with_picture %>
<% end %>

The logic is as follows:

Validation context of validates in the model context option of input Required
validates presence: true context: :with_picture required
validates presence: true, on: :with_picture none optional
validates presence: true, on: :with_picture context: :with_picture required

With the current feature set of simple_form, it is already possible to define the context option for the whole form:

<%= simple_form_for @user, defaults: { context: :with_picture } do |f| %>
  <%= f.input :name %>
  <%= f.input :avatar %>
<% end %>

This would make working with validation contexts much easier, in my opinion 馃檪

Current Workaround

The required option on the input can be used already to control this behavior. However, determining whether there is a presence validator on the context requires extra code, and cannot be set on the whole form easily (cf. https://stackoverflow.com/a/14234720/1023963).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant