2

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

1
  • would validate :findUpperCaseLetter(username) not work there? Commented Nov 19, 2014 at 5:14

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

Isnt /[A-Z]+/ sufficient?
Hiya, this may well solve the problem... but it'd be good if you could edit your answer and provide a little more explanation about how and why it works :) Don't forget - there are heaps of newbies on Stack overflow, and they could learn a thing or two from your expertise - what's obvious to you might not be so to them.
I don't understand this regular expression /^(?=.*[A-Z]).+$/. Can you help to understand it?
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. Paste ^(?=.*[A-Z]).+$ in rubular.com, you will get to know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.