2013-02-08 22:52:56 +08:00
|
|
|
class UsernameValidator
|
|
|
|
|
|
|
|
def initialize(username)
|
|
|
|
@username = username
|
2013-02-09 03:12:48 +08:00
|
|
|
@errors = []
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
2013-02-09 03:12:48 +08:00
|
|
|
attr_accessor :errors
|
2013-02-08 22:52:56 +08:00
|
|
|
attr_reader :username
|
|
|
|
|
|
|
|
def user
|
|
|
|
@user ||= User.new(user)
|
|
|
|
end
|
|
|
|
|
|
|
|
def valid_format?
|
|
|
|
username_exist?
|
|
|
|
username_length_min?
|
|
|
|
username_length_max?
|
|
|
|
username_char_valid?
|
|
|
|
username_first_char_valid?
|
2013-02-09 03:12:48 +08:00
|
|
|
errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def username_exist?
|
2013-02-09 03:12:48 +08:00
|
|
|
return unless errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
unless username
|
2013-02-09 03:12:48 +08:00
|
|
|
self.errors << I18n.t(:'user.username.blank')
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def username_length_min?
|
2013-02-09 03:12:48 +08:00
|
|
|
return unless errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
if username.length < User.username_length.begin
|
2013-02-09 03:12:48 +08:00
|
|
|
self.errors << I18n.t(:'user.username.short', min: User.username_length.begin)
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def username_length_max?
|
2013-02-09 03:12:48 +08:00
|
|
|
return unless errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
if username.length > User.username_length.end
|
2013-02-09 03:12:48 +08:00
|
|
|
self.errors << I18n.t(:'user.username.long', max: User.username_length.end)
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def username_char_valid?
|
2013-02-09 03:12:48 +08:00
|
|
|
return unless errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
if username =~ /[^A-Za-z0-9_]/
|
2013-02-09 03:12:48 +08:00
|
|
|
self.errors << I18n.t(:'user.username.characters')
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def username_first_char_valid?
|
2013-02-09 03:12:48 +08:00
|
|
|
return unless errors.empty?
|
2013-02-08 22:52:56 +08:00
|
|
|
if username[0,1] =~ /[^A-Za-z0-9]/
|
2013-02-09 03:12:48 +08:00
|
|
|
self.errors << I18n.t(:'user.username.must_begin_with_alphanumeric')
|
2013-02-08 22:52:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|