Last active
January 2, 2016 15:39
-
-
Save gschorkopf/8324745 to your computer and use it in GitHub Desktop.
Extracts complex validators (source: https://github.com/bignerdranch/sciwatch/commit/1a8580bb8277885cf6140c3ff5334086c15c79c8)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
class User < ActiveRecord::Base | |
validates :password, complexity: true # You may also pass this a method that returns true/false | |
# ... | |
end | |
# app/validators/complexity_validator.rb | |
class ComplexityValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
record.errors.add(attribute, "must have a number") if value !~ /(?=.*\d)/ | |
record.errors.add(attribute, "must have a lowercase letter") if value !~ /(?=.*[a-z])/ | |
record.errors.add(attribute, "must have an uppercase letter") if value !~ /(?=.*[A-Z])/ | |
record.errors.add(attribute, "must have a special character") if value !~ /(?=.*[\W])/ | |
record.errors.add(attribute, "must have at least 8 characters") if value.length < 8 | |
end | |
end | |
# some view form that takes password, likely app/views/users/new.html.erb | |
#... | |
= f.input :password, label: "New Password", error_method: :to_sentence | |
#... | |
# Note: to_sentence is built into ActiveSupport, and helps us show all errors in a user-friendly way. | |
# (http://apidock.com/rails/ActiveSupport/CoreExtensions/Array/Conversions/to_sentence) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment