Nick
Nick

Reputation: 3090

How to validate that username does not start with certain string?

One of the variables in a User model is username. I would like to reserve usernames starting with "vondel" for something else. Therefore, I would like to make it invalid for a username to start with "vondel". How can I do this?

Below is my attempt to set the validations on username. However, generating a username that starts with "vondel" is still possible and generates no error message. Is there a way to do this with a regular expression?

before_save :downcase_username        # Method that converts username to all 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 with 'vondel'")
    end
  end

Upvotes: 2

Views: 2597

Answers (2)

Kache
Kache

Reputation: 16677

The most straightforward way is to use the starts_with? method:

test_string = "vondelfoo"
test_string.starts_with?("vondel") # => true

Just as an aside, I recommend you learn how to do this with a regex. Regexes are an invaluable tool, and you should definitely learn how to use them.

Also a tip - I've heard Rubular to be a good tool for getting started with Ruby regular expressions.

edit

the Tin Man brings up a good point - Regexps are a powerful but an overly complex solution for this problem. Although I highly recommend you learn how to use them, you should prefer the straightforward and simple solution here.

Upvotes: 3

spickermann
spickermann

Reputation: 106852

Just change the condition in your vondel_not_allowed method to:

def vondel_not_allowed
  if username.start_with?('vondel')
    errors.add(:username, "cannot start with 'vondel'")
  end
end

Upvotes: 1

Related Questions