views:

179

answers:

3

How can I validate Rails model string attribute that it belongs to specific language alphabet characters?

Thanks.

A: 

validates_format_of seems to be the right thing for you. the documentation says:

Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression provided.

  class Person < ActiveRecord::Base
    validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  end

Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.

A regular expression must be provided or else an exception will be raised.

bjelli
A: 

You'll want to validate the value of the attribute against a regular expression.

# Only match characters a-z
validates_format_of :attr, :with => /[a-z]/
Tate Johnson
ok, what if it is not english?
Bogdan Gusiev
Regular expressions can match any UTF8 encoded characters by including the `u` option. `'你'.match(/你/u) # => #<MatchData:0x5f9970>`
Tate Johnson
A: 

There's a library called whatlanguage that recognize the languages of the string, example:

require 'whatlanguage'
"Je suis un homme".language      # => :french

Works with Dutch, English, Farsi, French, German, Swedish, Portuguese, Russian and Spanish out of the box, so it recognize Cyrillic too.

Luke