Validate Japanese Character in Active Record Callback
cjk, rails-activerecord, ruby, ruby-on-rails, validation
Solution
The following code may just push you over the line to fulfil the exact requirement you've so far specified in the least possible time. It uses the Moji gem (Japanese documentation), which gives lots of convenience methods in determining the content of a Japanese language string.
It validates a maximum of 14 characters in a `name` that only consists of half-width characters, and a maximum of 7 characters for `name`s otherwise (including names that contain a combination of half- and full-width characters i.e. the presence of even one full-width character in the string will make the whole string be regarded as "full-width").
class Customer
validates_length_of :name, :maximum => 14,
:if => Proc.new { |customer| half_width?(customer.name) }
validates_length_of :name, :maximum => 7
:unless => Proc.new { |customer| half_width?(customer.name) }
def half_width?(string)
Moji.type?(string, Moji::HAN_KATA)
end
end
Assumptions made:
- Data encoding within the system is UTF-8, and gets stored as such in the database; any further necessary re-encoding (such as for passing the data to a legacy system etc) is done in another module.
- No automatic conversion of half-to-full width characters done before data is saved to database i.e. half-width characters are allowed in the database for reasons perhaps of legacy system integration, proper preservation of actual user input(!), and/or aesthetic value of half-width characters(!)
- Diacritics in half-width characters are treated as their own separate character (i.e. no parsing of カ and ゙ to be considered one character for purposes of determining string length)
- There is only one name field as you specify and not, say, four (for surname, surname furigana, given name, given name furigana) which is quite common nowadays.
Problem
I have a Japanese project that needs to validate a half width and full width Japanese character, 14 chars are allowed on half width and 7 characters on full width. Is there anyone who knows how to implement that? Right now on my model ``` class Customer validates_length_of :name, :maximum => 14 end ``` is not a good choice I'm currently using ror 2.3.5 Both fullwidth and halfwidth can be used