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
  • 17,309
  • 27
  • 96
  • 165

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
  • 399
  • 3
  • 20
Justin Morgan
  • 28,775
  • 12
  • 76
  • 104
  • @ream88 - Thank you; edited to remove `\p{L}` version. It was sloppy of me not to check with such a short regex. The `\p{L}` doesn't work--why? Is it not supported in Ruby regex? It works fine in .NET. – Justin Morgan Jul 20 '11 at 18:53
  • 1
    @Justin Morgan - And what about validating accented characters like à, è, é, ò, ... in the string? – Backo Jul 21 '11 at 00:52
  • @Backo - If you use [the `u` flag](http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm), it should match those. [Tested here](http://rubular.com/r/EMofPxqMXU). – Justin Morgan Jul 21 '11 at 14:40
  • @Volte - Would you care to elaborate? – Justin Morgan May 06 '14 at 18:25
  • @Volte - That's not really relevant to this question. We don't know anything about what he's trying to do. – Justin Morgan May 06 '14 at 21:55
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
  • 73,270
  • 19
  • 138
  • 185
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
  • 352
  • 3
  • 16