add custom validation method in Ruby on Rails - ruby-on-rails

I need create a method the custom validation called findUpperCaseLetter or similar
I have a attribute called password that belongs to the model called User
My method is somewhat similar to the following. The password attribute must have at least a uppercase letter
def findUpperCaseLetter(username)
username.each_char do |character|
return true if character=~/[[:upper:]]/
end
return false
end
I want add this validation to the User model
class User < ActiveRecord::Base
attr_accessible :user_name,:email, :password
validates_presence_of :user_name,:email, :password
validates_uniqueness_of :user_name,:email
????
end
I have already the following regular expreession
validates_format_of :password, :with => /^[a-z0-9_-]{6,30}$/i,
message: "The password format is invalid"
How I modify it for add the following
The password must have at least one uppercase letter

You don't need custom validation to do this, you can use regex to validate the format of password. Add this to your model
validates :password, format: { with: /^(?=.*[A-Z]).+$/, allow_blank: true }
In Rails, you can do this by using format validator, I have added allow_blank: true to make sure when the field is empty it only throws Can't be blank error message and not format validator error message.
The work of this regular expression is to allow the password to be saved in the database only if it contains at least one capital letter. I have created a permalink on rubular, click here http://rubular.com/r/mOpUwmELjD
Hope this helps!

Related

Custom Validations Rails Model

I have a contact form and would like to show individual messages depending on what has failed.I would like to use flash messages. So from what i have read so far i can create a custom method (or i think it just overrides the one in place?)
So for example, i want to validate the presence of the name field
Class Message
attr_accessor :name
validates :name, :presence => true
def validate
if self.name < 0
errors.add(:name, "Name cannot be blank")
end
end
end
Within my controller i normally use a generic message
flash.now.alert = "Please Ensure all Fields are filled in"
Is there a way to call the particular message that failed validation?
Thanks
There is a plugin available, u can follow the below url
https://github.com/jeremydurham/custom-err-msg
Check the method validates because you can pass a message argument with the desired message.
validates :name, :presence => {:message => 'The name can't be blank.'}

How to do a simple regex validation in rails

How can perform a reguler expression to validate for either - or _ in the person username. i dont want to accept any other character like .#()$etc just - or _ so the person can either have a name like mike, mikel_mark or mike-mark. very simple. Thank you
example:
validate_format_of :username, with: "...."
The Rails 3 way to do validations is the following:
validates :username, :format => {:with => /\A[0-9a-z_]+\Z/i}
The form of validate_format_of is more Rails < 3 like and followed the "type of validation" concept, whereas the validates form is attribute based (you write all validations that apply to the attribute in one statement).
Check out the docs here: http://apidock.com/rails/v3.2.13/ActiveModel/Validations/ClassMethods/validates

Validation for a certain action in ruby on rails

In my current ROR project I am using devise pluing for validation. In my change password form validation, I am using the following code in the user model
validates_presence_of :password, :password_confirmation
But I wants to validate is only for an action. I have a function in my user controller named update_password. I found the that I can assign the action as follows:
validates_presence_of :password, :password_confirmation, :on => :update_password
But its not working. Even if the password and password confirmation fields are empty, the form is submitted. Can anyone help me to solve how to set the validation only for a particular action. Will be a great help
Thanks a lot
You can use :validatable option implemented in devise.
Just add to your model
devise :validatable
And set validation options in your config/initializers/devise.rb file
# ==> Configuration for :validatable
# Range for password length. Default is 6..128.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^#]+#[^#]+\z/
Another way is to use your own regexp validations. You can add to your model
validates :password, :format => { :with => /\A[a-zA-Z]+\z/, :message => "Only letters allowed" }
After that you can call #user.valid? in your controller to check that your user instance is correct.
There are many different ways to validate your model.
You can read more about validation and ActiveRecord callbacks in guides: http://guides.rubyonrails.org/active_record_validations_callbacks.html
If you're using devise, there's no need to check for that. It's handle for you by default.

Multiple validation error issue while saving a model in rails 3

I am having an issue while saving a user object in the database. I have two fields in the model (email and password) which are not allowed to be null in the database itself. Plus I have added validation in the model like
validates_presence_of :email, :message => "must be provided"
validates_presence_of :password, :message => "must be provided"
Now when I try to save the model from the create method of the controller, it invalidates the data and renders the new action again. However I have multiple error messages for each field
Email can't be blank
Email must be provided
Password can't be blank
Password must be provided
I don't need multiple error messages for the same one. How can I eliminate this?
Looks like you are validating in two different places. You have to figure it out the places...
If you are doing two different validation for a field and want to display one error message on a field at a time, you can do the following,
validates_presence_of :email, :message => "must be provided"
validates_uniqueness_of :email, :message => "must be unique",
:if => lambda { |a| a.errors.on(:email).blank? }
Looks like you are rendering errors twice. Check all your views, they can also be inherited.

In Rails 3, how can I skip validation of the password field when I'm not attempting to update the password?

My User model contains :name, :email, and :password fields. All 3 have validations for length. An "update account" web page allows the user to update his name and email address, but not password. When submitted, params[:user] is
{"name"=>"Joe User", "email"=>"user#example.com"}
Note there is no "password" key because the form doesn't contain such an input field.
When I call
#user.update_attributes(params[:user])
the password validation fails. However, since I'm not attempting to update the password, I don't want the password validation to run on this update. I'm confused why the password validation is running when params[:user] doesn't contain a "password" key.
Note that I want to have a separate web page elsewhere that allows the user to update his password. And for that submission, the password validation should run.
Thank you.
My application does something like this
attr_accessor :updating_password
validates_confirmation_of :password, :if => should_validate_password?
def should_validate_password?
updating_password || new_record?
end
so you have to model.updating_password = true for the verification to take place, and you don't have to do this on creation.
Which I found at a good railscast at http://railscasts.com/episodes/41-conditional-validations
In your user model, you could just ignore the password validation if it's not set.
validates_length_of :password, :minimum => N, :unless => lambda {|u| u.password.nil? }
Using update_attributes will not change the value of the password if there is no key for it in the params hash.
Validation doesn't run against the changed fields only. It validates existing values too.
Your validation must be failing because the password field contains some invalid content that's already saved in the database. I'm guessing it's probably because you're hashing it after validation and you're trying to validate the hashed string.
You can use a virtual attribute (an instance variable or method) that you validate with a custom method, and then assign the hash to the stored password field. Have a look at this technique for ideas.
An app that I am working on uses the following:
validates_confirmation_of :password,
:if => Proc.new { |account|
!account.password.blank?
|| !account.password_confirmation.blank?
|| account.new_record? }
Depending on your requirements, you might want to remove the new_record? check
When password is added then only confirmation will be called and presence will call on create action only
**validates_presence_of :password, :on =>:create**
**validates_confirmation_of :password**

Resources