Uchenna
Uchenna

Reputation: 4089

How to do a simple regex validation in rails

How can perform a reguler expression to validate for either - or _ in the person username. i dont want to accept any other character like .@()$etc just - or _ so the person can either have a name like mike, mikel_mark or mike-mark. very simple. Thank you

example:

validate_format_of :username, with: "...."

Upvotes: 0

Views: 203

Answers (1)

Christoph Petschnig
Christoph Petschnig

Reputation: 4147

The Rails 3 way to do validations is the following:

validates :username, :format => {:with => /\A[0-9a-z_]+\Z/i}

The form of validate_format_of is more Rails < 3 like and followed the "type of validation" concept, whereas the validates form is attribute based (you write all validations that apply to the attribute in one statement).

Check out the docs here: http://apidock.com/rails/v3.2.13/ActiveModel/Validations/ClassMethods/validates

Upvotes: 1

Related Questions