DEV Community

Cover image for Rails Password Validation
chowderhead
chowderhead

Posted on • Edited on

Rails Password Validation

Photo Cred: @breadboyshaun

FEBRUARY 15, 2020

Validate Users Model Password

Alright lets re invent the wheel for funsies. Why? because its saturday night and i want something fun to do- before all these people come trash my house.

Assumptions

  • you know how to Ruby on Rails
  • you have a user model set up with a password field

Why?

I wrote this because i wanted to throw individual errors for each requirement they were missing. Thank you stack overflow ! I didn't cite my sources , but check the stack youll find them.

What we are building:

Alt Text

Code

class User < ApplicationRecord
  validate :password_lower_case
  validate :password_uppercase
  validate :password_special_char
  validate :password_contains_number

  def password_uppercase
    return if !!password.match(/\p{Upper}/)
    errors.add :password, ' must contain at least 1 uppercase '
  end

  def password_lower_case
    return if !!password.match(/\p{Lower}/)
    errors.add :password, ' must contain at least 1 lowercase '
  end

  def password_special_char
    special = "?<>',?[]}{=-)(*&^%$#`~{}!"
    regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/
    return if password =~ regex
    errors.add :password, ' must contain special character'
  end

  def password_contains_number
    return if password.count("0-9") > 0
    errors.add :password, ' must contain at least one number'
  end
end

Enter fullscreen mode Exit fullscreen mode

We use errors.add to add message to the error messages on attribute. More than one error can be added to the same attribute. If no message is supplied, :invalid is assumed. ruby docs

Notice we have some sick regular expressions i got off stack overflow

in each of these validations, we return if the field matches the requirements, if it doesn't we use errors.add to bubble up some sick errors.

This shit is so open source, please use as you will my friends!

happy coding!

Top comments (0)