8

I am using Ruby on Rails 3.0.9 and I would like to validate a string that can have only characters (not special characters - case insensitive), blank spaces and numbers.

In my validation code I have:

validates :name,
  :presence   => true,
  :format     => { :with => regex } # Here I should set the 'regex'

How I should state the regex?

Backo
  • 18,291
  • 27
  • 103
  • 170

3 Answers3

19

There are a couple ways of doing this. If you only want to allow ASCII word characters (no accented characters like Ê or letters from other alphabets like Ӕ or ל), use this:

/^[a-zA-Z\d\s]*$/

If you want to allow only numbers and letters from other languages for Ruby 1.8.7, use this:

/^(?:[^\W_]|\s)*$/u

If you want to allow only numbers and letters from other languages for Ruby 1.9.x, use this:

^[\p{Word}\w\s-]*$

Also, if you are planning to use 1.9.x regex with unicode support in Ruby on Rails, add this line at the beginning of your .rb file:

# coding: utf-8
msdundar
  • 458
  • 4
  • 21
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
2

You're looking for:

[a-zA-Z0-9\s]+

The + says one or more so it'll not match empty string. If you need to match them as well, use * in place of +.

Mrchief
  • 75,126
  • 20
  • 142
  • 189
0

In addition to what have been said, assign any of the regular expresion to your regex variable in your control this, for instance

regex = ^[a-zA-Z\d\s]*$
dev
  • 382
  • 1
  • 3
  • 17