Quick tip - Unicode validations

July 3rd, 2006 Quick tipsRails

Are you doing regular expression validations in your Active Record models like this?

class User < ActiveRecord::Base
    validates_format_of :name, :with => /^\w{4,30}$/
end

Be aware that unless you enable unicode support these regular expressions will fail on many national characters.
Run the following to see this in action:

# test_expressions.rb
puts 'jose' =~ /^\w{4,30}$/     # match
puts 'josé' =~ /^\w{4,30}$/     # no match
$KCODE = 'u'
puts 'jose' =~ /^\w{4,30}$/     # match
puts 'josé' =~ /^\w{4,30}$/     # match

So in order to allow national character support in you apps simply add the following line to your environment.rb:

# environment.rb
$KCODE = 'u'    # enable unicode support

Now your Active Record models can truly validate in style.

--- --- ---

Commenting is closed for this article.