Robert Klubenspies
Robert Klubenspies

Reputation: 438

How do I validate that a screen name does not have any symbols or spaces with regex?

How would you validate a screen name using regex (on Ruby on Rails)?

I'm looking for a bit of regex to validate (in an RoR model) that a screen name does not have any symbols or spaces in it.

Upvotes: 0

Views: 882

Answers (2)

David Grayson
David Grayson

Reputation: 87396

It sounds like you want to specify a blacklist of characters that aren't allowed, but there are a lot of characters out there that you probably don't want in screen names so it would be better to use a whitelist. Here's an example that would only allow letters, numbers, and underscores in screen names and restrict the length to be 2-30:

class User < ActiveRecord::Base
    validates_format_of :screen_name, :with => /\A[a-zA-Z0-9_]{2,30}\Z/
end

Upvotes: 7

Samwhoo
Samwhoo

Reputation: 312

if string =~ /^[A-Za-z0-9]+$/
  # name is valid
else
  # name is not valid

I believe that will work :)

Upvotes: 0

Related Questions