I want to validate a string attribute is not nil, but allow empty strings.
As in:
validates name: not_nil, allow_empty: true
you could also do:
validates :name, exclusion: { in: [nil] }
To allow an empty string, but reject nil in an active record validation callback, use a conditional proc to conditionally require the presence of the attribute if it's not nil.
So the code looks like:
validates :name, presence: true, if: proc { name.nil? }
But you probably want to allow null. Then don't validate. Still check for presence? in code for nil or empty string.
Alternatively
validates :name, presence: true, allow_blank: true
Related
Thank you for looking onto this. I have a rails 5 API application. I am using ActiveModel Validations to validate params.
I need to validate the keys of params. ie. all the keys are mandatory to keep the structure of request unique, but it can be blank(ie. the values)
I know the
validates :key presence: true
validation, but it is checking there is a value for that. As i said, it can have blank values.
I am using params.permit so that additional keys are not allowed
include ActiveModel::Validations
validates :key1, presence: true
def initialize
#key1 = "val"
#key2 = "val2"
params.permit(:key1,:key2)
end
I need to compel the user to do requests with all the parameters with blanks allowed
Thanks in advance
Hello you should add the allow_blank options to your model like this:
validates :key presence: true, :allow_blank => true
Hope it can help
From the doc you need to specify allow_blank like :
validates :key1, :presence => true, :uniqueness => { :allow_blank => true, :case_sensitive => false }
Hope this helps !
You can try like below:
validates :key, presence: true, allow_blank: true
allow_blank:
The :allow_blank option is similar to the :allow_nil option.This option will let validation pass if the attribute's value is blank?, like nil or an empty string for example.
Note: nil values will be allowed
In my rails application, I have bank_details table with columns - account_number, ifsc_code, bank_name and branch_code(Only for India). But I don't know how to validates this columns before save it to database.Plese help me in this.
I will appreciate your help.
Thanks in advance.
In your model, you need to add a validates: your_column.
For example if you want to make sure that account number is present before you save to the database, you need to add validates: account_number, presence: true
There are both pre-built helpers, so you can validate by presence, name, etc, but you can also use a custom method to validate those.
Check out RailsGuides for all the details
There are so many validation that you can apply on your columns, here is a list of possible validation. you can pick as your requirement.
Validation for data should be present
validates :account_number, :ifsc_code, :branch_code, :bank_name, presence: true
data should be positive numbers only
validates :account_number, :branch_code, :numericality => { :greater_than_or_equal_to => 0 }
set length of record
validates :ifsc_code, length: { is: 11 }
validates that the attribute's value is unique right before the object gets saved
validates :account_number, uniqueness: true
In your model you can have something like this:
validates: branch_code
which is a standard validation, making sure its present
Or you can do more validation using regex
validates :bank_name, format: { with: /\A[a-zA-Z]+\z/,
message: "only allows letters" }
Here are some examples of validation:
validates :bank_name, length: { minimum: 2 }
validates :bank_name, length: { maximum: 500 }
validates :bank_name, length: { in: 6..20 }
validates :bank_name, length: { is: 6 }
Or use some advance techniques like so:
validates :bank_name, presence: true, if: "branch_code.nil?"
TransferWise provides an API you can use to validate IFSC codes and Indian account numbers:
IFSC code
https://api.transferwise.com/v1/validators/ifsc-code?ifscCode=YESB0236041
Account number
https://api.transferwise.com/v1/validators/indian-account-number?accountNumber=678911234567891
Documentation here.
I have a model Order with the price attribute.
There are few Order records in the database without a price attribute(nil value) which was imported from the old database. There are less than 20 invalid records like this.
Now the price attribute is mandatory.
I need to add a presence validation of the price and preserve the old records.
I can't set the nil values to zero or some random values.
I have some crazy ideas about the conditional validation on the basis of the timestamp or even a list of "permitted" ids.
Something like this:
PERMITTED_IDS = [4, 8, 15, 16, 23, 42]
validates :price, presence: true, if: -> { |order| PERMITTED_IDS.exclude?(order.id) }
Is there any nice and convenient way for that?
Use on: :create
The following will only validate when the model is created.
validates :price, presence: true, on: :create
However, can't you just use allow_nil: true:
validates :price, presence: true, allow_nil: true
I would add a boolean imported attribute to the Order class, setting it to true for old records upon import. This allows you to skip validations for these records easily:
validates :price, presence: true, unless: :imported?
UPDATE
Stefan: Are old/imported records editable?
freemanoid: #Stefan yes, but I can't set the price to zero for them.
The above solution is not an option because it would allow a nil price for all old records.
You could use a custom validation that requires a price for new records, but allows nil when updating records if the price was already nil. Something like:
validates :price, presence: true,
on: :create
validates :price, presence: true,
on: :update,
unless: Proc.new { |o| p.price_was.nil? }
In my validations, I have already used once a conditional presence like
validates :contact_name, presence: true
validates :contact_adress,
presence: true, if: :contact_name?,
Now I would like to do the contrary: condition the obligation of an attribute to the absence of the other attribute. If I let A empty, then B has to be filled and vice versa.
Would that work?
validates :attribute_A, presence true, if:attribute_B!
validates :attribute_B, presence true, if:attribute_A!
You can use unless or .blank?
validates :attribute_A, presence true, if: :attribute_B.blank?
OR
validates :attribute_A, presence true, unless: :attribute_B
From documentation of validates
There is also a list of options that could be used along with validators:
...
:unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.
However, it may be more clear to use if: with the help of Object#present? or Object#blank?.
I have a field in a form which is optional but if it is completed I want to validate that it is an integer value. In my model I have:
validates :number_of_employees, numericality: { only_integer: true }
This works but when I submit the form with the value not completed it raises an error because it is not numeric. I gather you can put and if condition in the validates statement but not sure if this is the correct way to handle this or what the syntax is to check for existance.
Any help appreciated.
Rather than using an :if option, the idiomatic way to allow empt fields to pass validation is to use the :allow_blank option. It's common to all the validators except the presence validator.
validates :number_of_employees, numericality: { only_integer: true, allow_blank: true }