# How to validate password complexity

**URL:** <https://www.ruby-forum.com/t/how-to-validate-password-complexity/144549>\
**Category:** Rails\
**Created:** [July 30, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/how-to-validate-password-complexity/144549 "2008-07-30T21:06:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![GreenValley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f14d63/32.png) [@GreenValley](https://www.ruby-forum.com/u/GreenValley)\
**Post date:** [July 30, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/how-to-validate-password-complexity/144549/1 "2008-07-30T21:06:11Z")

</div>

Hi,

I have a user model that saves password\_salt and password\_hash in DB,  
there is no password attribute. I would like to validate the password  
complexity with regular expression, but because password is not an  
attribute validation always fails. How can I accomplish this  
validation using the validation framework?

Thanks.

class User \< ActiveRecord::Base  
validates\_format\_of :password,  
:with =\> /^._(?=.{6,})(?=._\d)(?=._[a-z])(?=._[A-Z]).\*$/

def password=(pass)  
salt = [Array.new(6){rand(256).chr}.join].pack(“m”).chomp  
self.password\_salt, self.password\_hash =  
salt, Digest::SHA256.hexdigest(pass + salt)  
end

def password  
end  
end

---

<div class="post-metadata">

**Author:** ![GreenValley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f14d63/32.png) [@GreenValley](https://www.ruby-forum.com/u/GreenValley)\
**Post date:** [July 31, 2008, 9:54am UTC](https://www.ruby-forum.com/t/how-to-validate-password-complexity/144549/2 "2008-07-31T09:54:51Z")

</div>

On Wed, Jul 30, 2008 at 2:40 AM, GreenValley [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Hi,
> 
> I have a user model that saves password\_salt and password\_hash in DB,  
> there is no password attribute. I would like to validate the password  
> complexity with regular expression, but because password is not an  
> attribute validation always fails. How can I accomplish this  
> validation using the validation framework?

You can always override validate or validate\_on\_create

See: [Peak Obsession](http://api.rubyonrails.com/classes/ActiveRecord/Validations.html)

---

<div class="post-metadata">

**Author:** ![GreenValley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f14d63/32.png) [@GreenValley](https://www.ruby-forum.com/u/GreenValley)\
**Post date:** [July 31, 2008, 1:19pm UTC](https://www.ruby-forum.com/t/how-to-validate-password-complexity/144549/3 "2008-07-31T13:19:14Z")

</div>

Thank you Christopher. I will do that.
