I have on my form two fields:
phone and mobile phone
I would like to use one method to validate two fields with one the same method how to do it??
Any validation can be used for any number of attributes. For example:
validates_presence_of :foo, :bar
If you're using a custom validation method, just make sure it inspects both attributes - something like this:
validate :phone_format
def phone_format
[phone, mobile].each do |attr|
errors.add(attr, "some error message") unless attr =~ /some regex/
end
end
Check out http://guides.rubyonrails.org/active_record_validations_callbacks.html
Write a custom validator
Related
Is it possible to make a attribute required just for a particular form?
The field is nullable in the model, and there is no validation setup for it currently and I want to keep it that way.
But on 1 form, I would like to make the field required.
Is this possible without creating a separate model for this?
You could use ActionControllers require for the used parameters, something like this:
def person_params
params.require(:person).permit(:name).tap do |person_params|
person_params.require(:name) # SAFER
end
end
http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require
Does that help you?
I know that you doesn't want to touch the model, but you can do a conditional validation like this that isn't invasive
validates_presence_of :your_attribute, :if => :from_specific_form?
and create some methods that work with this
private
def from_form
#from_specific_form = true
end
def from_specific_form?
#from_specific_form
end
Then when you want the validation to work, just do something like this
xyz = YourModel.new
xyz.from_form
I have a Model called Person.
class Person < ActiveRecord::Base
validate_presence_of :name
validate :check_card_number
def check_card_number
errors.add(:card_number, "Card Number can't be blank") if card_number.blank?
-----
# some other stuffs here
----
end
end
If I am calling the below method I am getting the validator class name
Person.validators_on(:name) => [ActiveModel::Validations::PresenceValidator]
but for
Person.validators_on(:card_number) => []
How can I check I am validating the presence of card number?
validate method actually inserts a method(which is passed as an argument) into a callback chain. Because, it doesn't use any defined validators from ActiveModel. So, it can be accessed like so:
Person.send(:get_callbacks, :validate).detect{ |cb| cb.filter == :check_card_number }
However, condition in method "card_number.blank?" looks from presence of card_number attribute. Which in my guess would be a good fit for:
validate_presence_of :name, :card_number
Try this:-
ModelName._validate_callbacks.to_a.reject { |validation| validation.filter.to_s.starts_with?('validate_associated_records') }
Here 'reject' is used to ignore some default validations.
I doubt this is possible. Just tried Person.validators but it does not return custom validation methods.
If you really want validators_on and validators to return all validators, you can create a custom ActiveModel::Validator class and register it in your model with validates_with.
I have a search form with many fields. Each field is a parameter for searching a very large database. These parameters are passed to a search object. Some combinations of parameters are valid, others are not (they put too heavy a load on the system). What is the best way to write validations for combinations of parameters? For example: You should be able to search by name and one other field, but not name alone. In some cases if you enter a value in one field, you cannot enter a value in others
Currently I have something like this in my search class.
SEARCHABLE_ATTRIBUTES = [:name, :city, :state, :phone, :invoice_number, :payment_amount, :payment_date, :current_balance]
validate: valid_combinations
def valid_combinations
unless name.present? && (SEARCHABLE_ATTRIBUTES - [:name, :invoice_number]).select{|sa| send(sa).present?}.any?
errors.add(:name, "can't be given alone.")
end
if name.present? && invoice_number.present?
errors.add(:invoice_number, "can't be searched with name")
end
end
My valid search param restrictions get more complex than this, but this is just an example. Is there a better way to do this? I'd like to avoid one big valid_combinations method.
You can pass a condition to the validation and it will run only if that condition returns true.
So you could create separated validation methods and use them like this:
validate :at_least_another_column, if: Proc.new{|record| record.name }
Or, if you create a condition method named name_present you could code it like this:
validate :at_least_another_column, if: :name_present
To substitute your second condition you could use:absence and :message options. Looking like this:
validates :invoice_number, absence: true, if: :name_present , message: "can't be searched with name"
As you can see the code becomes much cleaner and understandable when using separated validations. But depending on how complex your conditions may be, it could be easier to create a giant validator method
There's a lot more about validations here
Is it possible to pass :symbols to the valid? method so that I can define if the object is valid up to a certain point?
Eg. if I have an object Person and want to call Person.valid?(:basic_info) and it will return true only if a certain subset of fields (say name & gender) are present?
I saw something that I thought might be of use but cannot get it working, it's conditional validations http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation , in particular grouping conditional validations, but I couldn't get it working...
Can anyone help me out here please...
I don't think there already present like this however you can write a method on your own like following
def is_valid_field?(field)
self.valid?
self.errors[field].blank?
end
and then just person.is_valid_field?(:basic_info)
To validate basic_info you'll have to define a custom validator:
class Person < ActiveRecord::Base
validate :basic_info_present
def basic_info_present
if name.blank? || gender.blank?
errors.add(:basic_info, "can't be in blank")
end
end
end
If you then want to see if there are errors on the specific field, you can use #Salil's approach.
Note however that since there is no actual attribute called basic_info in your model, the validation errors here will not come up in forms, etc. (although they will be in the errors hash). That may or may not be what you want.
I got this to work using conditional validations, so now i can use .valid?(:basic) say for when i only want to check that the person has a name with the call...
validates_presence_of :name, :when => [:basic]
Documentation here: http://apidock.com/rails/ActiveRecord/Validations/valid%3F
This way I can have the object return true when calling .valid? even when it doesn't have a name, good times...
I know ActiveRecord provide some macros like validates_uniqueness_of validates_size_of
to do some validation for the user input. but I'm wondering whether it is possible to provide
some call-back like validation method to be used as a cutomised validation method in the model level. for example,
I want to check the input string only consits of letters from 'a' to 'h', funny? but it happened from time to time.
You can create custom functions with:
validate :custom_function
def custom_function
...
end
You can also use regular expressions to validate strings. For your example I would use:
validates_format_of :attribute, :with => /^[a-h]+$/
The rails guides has a good example of how to create your own custom validators. If you are using Rails 3 you could do it like this:
class Foo < ActiveRecord::Base
validate :from_a_to_h
# Use the name of your attribute in place of :input and input.
def from_a_to_h
errors.add(:input, "must contain only letters from a to h") if input =~ /[i-Z]+/
end
end