perform one validation only if all other validations pass
You could check the errors
array and return.
def check_valid_bank_account
return unless errors.blank?
…
end
Adding validation rule only if all other rules pass, or stop validating entire set of attributes on the first error in Laravel 5.7
I have finally found the solution myself. Here is what I ended up with.
To achieve the desired result I created another validator in withValidator()
method of my custom form request, this second validator will handle only the FolderExists
rule and only if the previous validation fails.
public function rules()
{
return [
'asset-id' => ['bail', 'required', 'integer', 'exists:assets,id'],
'relative-path' => ['bail', 'required', 'string'],
'new-folder-name' => ['bail', 'required', 'string', 'min:3', 'max:150', new FolderName]
];
}
public function withValidator($validator)
{
if (!$validator->fails())
{
$v = Validator::make($this->input(),[
'new-folder-name' => [new FolderExists($this->input('asset-id'), $this->input('relative-path'))]
]);
$v->validate();
}
}
If our main validator passes, we make another validator and pass only FolderExists
rule with its arguments, that have already been validated, and call validate()
method. That's it.
Running rails inclusion validation only if presence passes
pass in an if
inside the inclusion
option to check for the presence
validates :segment_type,
presence: true,
inclusion: { in: SEGMENT_TYPES, if: :segment_type_present? }
private
def segment_type_present?
segment_type.present?
end
you can also use a proc
inclusion: { in: SEGMENT_TYPES, if: proc { |x| x.segment_type.present? } }
Rails - Validation :if one condition is true
You can use a lambda for the if:
clause and do an or condition.
validates :description, presence: true, if: -> {current_step == steps.first || require_validation}
Need to run the validation one after check another on Rails
You can use a Proc here:
validates :email, :presence
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, message: 'Invalid email address', :if => Proc.new { |o| o.errors.empty? }
validates_uniqueness_of :email, case_sensitive: false, message: 'Email has already been entered', :if => Proc.new { |o| o.errors.empty? }
Validate presence of field only if another field is blank - Rails
You don't need a lambda. This will do:
validates_presence_of :mobile_number, :unless => :home_phone?
Also, all of the validators take the same if/unless options, so you can make them conditional at will.
Update: Looking back at this answer a few days later, I see that I should explain why it works:
- If you set a validator's
:unless
option to be a symbol, Rails will look for an instance method of that name, invoke that method on the instance that's being validated -- at validation time -- and only perform the validation if the method returns false. - ActiveRecord automatically creates question mark methods for each of your model's attributes, so the existence of a
home_phone
column in your model's table causes Rails to create a handy#home_phone?
method. This method returns true if and only if home_phone is present (i.e. not blank). If the home_phone attribute is nil or an empty string or a bunch of white space, home_phone? will return false.
UPDATE: Confirmed that this old technique continues to work in Rails 5.
Related Topics
How to Fix Libv8 Error from Gemfile on Mavericks
Deleting the Current Session with Rack::Session::Cookie
How to Escape a Single Quote in Ruby
Rails First_Or_Create Activerecord Method
Ruby, Using Regex to Find Something in Between Two Strings
Is It a Bad Idea to Reload Routes Dynamically in Rails
Setting Up Env, Osx Rbenv and Bundle Battle
Capistrano 3 + Sprockets 3 + Rails 4.2.1 Won't Deploy
Actiondispatch::Http::Uploadedfile.Content_Type Not Being Initialized in Rspec Test
Using Activerecord Interface for Models Backed by External API in Ruby on Rails
Ruby Code Beautification, Split Long Instructions on Multiple Lines
Ruby Array to Hash: Each Element the Key and Derive Value from It
How to Color Unit Tests with Lib Minitest or Test:Unit
How to Allow Binary File Download Using Grape API
How to Get a Substring from Position N to the Last Char in Ruby
How to Run a Simple Ruby Script in Any Web Server (Apache or Mongrel or Any Thing Else)