Module: Fend::Plugins::ValidationOptions
- Defined in:
- lib/fend/plugins/validation_options.rb
Overview
Instead of calling ValidationHelpers::ParamMethods separately, you can use ‘validation_options` plugin in order to specify all validations as options and pass them to `Param#validate` method.
plugin :validation_options
validate do |i|
i.params(:email) do |email|
email.validate(presence: true, type: String, format: EMAIL_REGEX)
end
end
## Custom error messages
Custom error messages can be defined with ‘:message` option:
email.validate(presence: { message: "cannot be blank"})
## Mandatory arguments
For ValidationHelpers::ParamMethods that expect mandatory arguments, there are predefined option keys that you can use. To see them all check MANDATORY_ARG_KEYS constant.
email.validate type: { of: String, message: "is not a string" }, format: { with: EMAIL_REGEX }
account_type.validate inclusion: { in: %w(admin, moderator) }
You can also use the DEFAULT_ARG_KEY (‘:value`) if you find it hard to remember the specific ones.
email.validate type: { value: String }, format: { value: EMAIL_REGEX }
## Allowing nil and blank values
You can skip validation if param value is ‘nil` or blank by passing `:allow_nil` or `:allow_blank` options:
# will skip type validation if name.value.nil?
name.validate(type: String, allow_nil: true)
# will skip type validation if email.blank?
email.validate(type: String, allow_blank: true)
To see what values are considered as blank, check ValueHelpers::ParamMethods#blank?.
‘validation_options` supports ExternalValidation plugin:
plugin :external_validation
# ...
email.validate(with: CustomEmailValidator)
Defined Under Namespace
Modules: ParamMethods
Constant Summary collapse
- NO_ARG_METHODS =
[:absence, :presence, :acceptance].freeze
- ARRAY_ARG_METHODS =
[:exclusion, :inclusion, :length_range].freeze
- DEFAULT_ARG_KEY =
:value
- MANDATORY_ARG_KEYS =
List of keys to use when specifying mandatory validation arguments
{ equality: :value, exact_length: :of, exclusion: :from, format: :with, greater_than: :value, greater_than_or_equal_to: :value, gteq: :value, inclusion: :in, length_range: :within, less_than: :value, less_than_or_equal_to: :value, lteq: :value, max_length: :of, min_length: :of, type: :of }.freeze
Class Method Summary collapse
-
.load_dependencies(validation, *args, &block) ⇒ Object
Depends on ValidationHelpers plugin.
Class Method Details
.load_dependencies(validation, *args, &block) ⇒ Object
Depends on ValidationHelpers plugin
85 86 87 |
# File 'lib/fend/plugins/validation_options.rb', line 85 def self.load_dependencies(validation, *args, &block) validation.plugin(:validation_helpers) end |