LoginSignup
16
6

More than 5 years have passed since last update.

UTF-8で4バイト以上の文字を判定するカスタムバリデータをつくる

Last updated at Posted at 2018-08-16

はじめに

DBがUTF-8の4バイト以上の文字に対応してなかったので、アプリケーション側で対応します :muscle:

環境

ruby 2.5.1
Rails 5.0.6

カスタムバリデータをつくる

今回、個別の属性を検証したかったので、ActiveModel::EachValidatorを利用します。
Active Record バリデーション | Rails ガイド

class Lt4bytesValidator < ActiveModel::EachValidator
  # UTF-8で4バイト以上の文字かを判定する
  def validate_each(record, attribute, value)
    return if value.blank?

    unavailable_chars = value.scan(/[^\u0000-\uFFFF]/)

    record.errors.add(attribute, :unavailable, chars: unavailable_chars.uniq.join(', ')) if unavailable_chars.present?
  end
end

localeもちゃんと設定しましょう :bulb:

ja:
  errors:
    messages:
      unavailable: 'に使用できない文字(%{chars})が含まれています。'

モデルに取り込む

今回作成したLt4bytesValidatorを使うにはlt4bytesオプションを渡せばOKです :ok_hand:

class Article < ApplicationRecord
  validates :content, lt4bytes: true
  ...

挙動チェック

rails consoleで試してみます。

article = Article.new
article.content = '🤓'
article.validate
article.errors[:content]
=> ["に使用できない文字(🤓)が含まれています。"]

以上です。

それでは〜 :wave:

参考

16
6
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
6