ruby on rails - How to validate that username does not start with certain string? -
one of variables in user model username
. reserve usernames starting "vondel" else. therefore, make invalid username
start "vondel". how can this?
below attempt set validations on username
. however, generating username
starts "vondel" still possible , generates no error message. there way regular expression?
before_save :downcase_username # method converts username downcase. valid_username_regex = /\a[a-za-z0-9_-]+\z/i validates :username, presence: true, length: { in: 6..15 }, format: { with: valid_username_regex }, uniqueness: { case_sensitive: false } validate :vondel_not_allowed private def vondel_not_allowed if username == "vondel*" errors.add(:username, "username cannot start 'vondel'") end end
the straightforward way use starts_with?
method:
test_string = "vondelfoo" test_string.starts_with?("vondel") # => true
just aside, recommend learn how regex. regexes invaluable tool, , should learn how use them.
also tip - i've heard rubular tool getting started ruby regular expressions.
edit
the tin man brings point - regexps powerful overly complex solution problem. although highly recommend learn how use them, should prefer straightforward , simple solution here.
Comments
Post a Comment