Ruby on rails validation - ruby-on-rails

I figured a way to do validation. I found that inside models, i need to add these lines
validates_presence_of :name
validates_uniqueness_of :name
What i'm trying to achieve is for example, i don't want the user to add :;!##$%^&*() [or special characters] in my text inputs. Need some inputs on this.

You can use format_of:
validates_format_of :name, :with => /\A[a-zA-Z]+([a-zA-Z]|\d)*\Z/
Or create your own validation:
validates :name,
:presence => true,
:format => { :with => regex } # Here you can set a 'regex'

Related

Input validations on fields in ActiveAdmin

When I create a new form in ActiveAdmin, I want validations on my form input fields. But I can't find a related tutorial. I want some fields to accept only alphabets, some only digits , and some should be of specific length.
f.input :name, :label => "Title", input_html: { autofocus: true }
f.input :description
f.input :email
f.input :contact_number
f.input :contact_person
[Answer not only for ActiveAdmin, but for RoR in general]
You should do it in model.
• For digits only:
You want your :contact_number to be a digit, so your model (e.g. User) should look like this:
class User < ActiveRecord::Base
validates :contact_number, numericality: {only_integer: true}
end
• For min. 5 characters:
If description for example must be at least 5 characters it will be:
validates_length_of :description, minimum: 5
• For letters only:
validates_format_of :name, with: /^[-a-z]+$/
(details about reg. expressions --> Validate: Only letters, numbers and - )
Additional info:
If your form don't pass model validation it will return alert about wrong argument (which is accessible in flash[:alert] array).
More about it in:
http://guides.rubyonrails.org/active_record_basics.html#validations
You can have the validations defined in your corresponding Model class.
See the official documentation for Rails validation.
ActiveAdmin will pick it up when you try to create/edit/update objects of that model if you have Rails standard validations or even custom validations defined in your Model class.
For example, for your email validation, you can have this in your model:
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
Then, when you try to create/save an object through ActiveAdmin, it will show you error if the email is not in the correct format.
So, you have to define all of your validations (for all the fields that you want) in your model. That's it!
And, to display a list of all validation errors, you have to do:
form do |f|
f.semantic_errors *f.object.errors.keys
# ...
end
Update
Add these validations to your Model class:
validates_presence_of :description
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates :contact_number, :presence => {:message => 'hello world, bad operation!'},
:numericality => true,
:length => { :minimum => 10, :maximum => 15 }
These are Rails standard validations. You can add custom validations to your model too.
For example, if you want to add a custom validation for the username, you can define that like this:
validate :username_must_be_valid
And, then define the custom validator method username_must_be_valid in the same model class like this:
private
def username_must_be_valid
errors.add(:username, 'must be present') if username.blank? && provider.blank?
end

Rails: How to set different validation rules on creation and update

I have a text field that can be empty when created, but not when updated.
How can I do that in rails: Different validation rules depending on action?
The idea behind this, is to allow an admin to create a blank issue ticket, to be filled by a user.
Here is my original model (issue.rb):
class Issue < ActiveRecord::Base
attr_accessible :content, :status
validates :content, :presence => true, :length => { :maximum => 2048 }
validates :status, :inclusion => { :in => %w(WAITING REJECTED ON OFF) }
belongs_to :user
end
How can I set :presence => true of :content only when updating, but not when creating?
Thanks in advance.
You can use :on => :create in your validation statement.
Like in this question.

Rails Validation that use validates a string with a regex?

I have a Message.uuid field which I want to add validations for which include:
Supported:
A-Z, a-z, 0-9
dashes in the middle but never starting or ending in a dash.
At least 5, no more than 500 characters
What is the best way in rails to write a model validation for these rules?
Thanks
UPDATE:
validates :uuid,
:length => { :within => 5..500 },
:format => { :with => /[A-Za-z\d][-A-Za-z\d]{3,498}[A-Za-z\d]/ }
With a valid UUID this is failing
I'd leave the length validation up to a validates_length_of validator, so that you get more specific error messages. This will do two things for you: Simplify the regex used with your validates_format_of validator, and provide a length-specific error message when the uuid is too short/long rather than showing the length error as a "format" error.
Try the following:
validates_length_of :uuid, :within => 5..500
validates_format_of :uuid, :with => /^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i
You can combine the two validations into a single validates with Rails 3:
validates :uuid,
:length => { :within => 5..500 },
:format => { :with => /^[a-z0-9][-a-z0-9]*[a-z0-9]$/i }
Use:
validates :uuid, :format => {:with => /my regexp/}
As for the regexp, you've already asked for it in another question.

Nested model validation context

I am using Ruby on Rails 3.0.9 and I am trying to validate a nested model in a specific context just for the email attribute uniqueness.
In my controller I have:
#user.valid? :uniqueness_context
In my nested model I have:
validates :email,
:format => {
:with => EMAIL_REGEX
},
:uniqueness => {
:on => :uniqueness_context # Here it doesn't work
},
:presence => true
What is wrong? How can I make the above validation code to work?
Notice: if in the model I use the following:
validates :email,
:format => {
:with => EMAIL_REGEX
},
:uniqueness => true,
:presence => true
all works as expected.
In order to solve the issue I have tried also to use the following in the model:
validates :email,
:format => {
:with => EMAIL_REGEX
},
:presence => true
validates_uniqueness_of :email, :on => :uniqueness_context
but it still doesn't work.
I ran into the same problem. Seems that Rails currently does not support custom validation contexts. :if will do the job for you.
Sorry, I spaced it for a minute because I didn't realize you could create a custom context.
Looking at the source, it doesn't appear that the UniquenessValidator supports the :on context option.
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/validations/uniqueness.rb

Rails model conditional vaidation

I validate fields in model using:
validates :first_name, :presence => true, :if => :should_validate?
validates :last_name, :presence => true, :if => :should_validate?
...
There are many fields in model that needs to be validated and it doesn't look good if I specify :if => method for each one.
Is it possible to embed this validates methods in block instead of giving :if => method for each one?
You could write your own custom validator of course, but if you're only validating presence, this might do the trick:
validates :first_name, :last_name, :presence => true, :if => :should_validate?
I don't think there is something out of the box for this. If you want, you can use a custom validator.
What are the conditions that you need this validated? If you don't need it validated couldn't you just leave that line out? Otherwise you could just validate on certain actions so you don't need to evaluate for should_validate?, for example:
validates :first_name, :last_name, :presence => true, :only => [:create, :update]

Resources