Validate a form field only if populated - ruby-on-rails

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 }

Related

Required Params Validations in Rails 5 API

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

Validate Rails attribute presence but allow empty string

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

How to validate bank details like account_number, ifsc_code, bank_name and branch_code etc... in Rails

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.

Difference between the presence and allow_blank validators in Rails?

I'm trying to figure out the difference between:
validates :foo, presence: false
validates :foo, allow_blank: true
When I use presence: false validation fails but when I use allow_blank: true it does not. According to the docs http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of uses the blank? method. Can someone please explain the difference?
First case:
validates :foo, presence: false
it does not validate the presence of :foo at all.
nil, '', 'anything' are all valid.
Second case: :allow_blank is an option, not a validator.
It skips validation if the attribute is blank (more here).
If you want to know how it works, you can see the code here.
Before call the selected validator, it checks the attribute is not blank, if it's then skip validation.
The only reason why it works as a validator is the way that source code is written.
At any moment Rails' team can change the code and :allow_blank stop working as a validator.
allow_blank only validates nil, presence validates nil as well as empty

Datatype model validation

In Ruby on Rails, I can't seem to find a validation model method to check for data-type.
I was hoping for something like
validates :name, datatype: :integer
but there is nothing on http://guides.rubyonrails.org/testing.html
If such a test not required? Is it because the database engine (mysql or whatever) itself would reject information with a wrong data-type?
It seems you are new to Rails there are already predefined validations in rails Ref Active Record Validations in Rails
validates :name, numericality: true
or
validates :name, numericality: { only_integer: true }
You can do something like
validates :your_field, :numericality => { :greater_than_or_equal_to => 0 }
please check the link
Validation for non-negative integers and decimal values
There is a validation for this in Rails
validates_numericality_of :value, :only_integer: true

Resources