EmojiValidator
A Rails engine that provides validators for emoji strings using the unicode-emoji gem.
Installation
Add this line to your application's Gemfile:
gem "emoji_validator"And then execute:
bundle installUsage
Default: Single Emoji Only
By default, the field must contain exactly one emoji (no text, no multiple emojis):
class Reaction < ApplicationRecord
validates :emoji, emoji: true
endreaction = Reaction.new
reaction.emoji = "😀" # ✓ Valid
reaction.emoji = "👋🏽" # ✓ Valid (with skin tone)
reaction.emoji = "Hello 😀" # ✗ Invalid - has text
reaction.emoji = "😀😁" # ✗ Invalid - multiple emojisOptions
allow_text: true
Allow text alongside the emoji (still only one emoji allowed):
class Message < ApplicationRecord
validates :content, emoji: { allow_text: true }
endmessage.content = "Hello 😀 World" # ✓ Valid
message.content = "😀" # ✓ Valid
message.content = "😀😁" # ✗ Invalid - multiple emojisallow_multiple: true
Allow multiple emojis (no text allowed):
class StickerSet < ApplicationRecord
validates :emojis, emoji: { allow_multiple: true }
endsticker.emojis = "😀😁🎉" # ✓ Valid
sticker.emojis = "😀" # ✓ Valid
sticker.emojis = "😀 Hello" # ✗ Invalid - has textBoth Options
Allow multiple emojis with text:
class Post < ApplicationRecord
validates :content, emoji: { allow_text: true, allow_multiple: true }
endpost.content = "🎉 Party time! 🎊" # ✓ Valid
post.content = "Hello World" # ✗ Invalid - no emoji
allow_blank / allow_nil
Allow empty strings or nil values:
class OptionalReaction < ApplicationRecord
validates :emoji, emoji: { allow_blank: true, allow_nil: true }
endCustom Error Message
class Reaction < ApplicationRecord
validates :emoji, emoji: { message: "pick one emoji" }
endDisallowing Emojis
In addition to requiring emojis, you can also validate that fields do not contain emojis.
no_emoji - Validate single attributes
class Person < ApplicationRecord
validates :first_name, no_emoji: true
endperson.first_name = "John" # ✓ Valid
person.first_name = "😃John" # ✗ Invalid - contains emoji
person.first_name = "Jo😃hn" # ✗ Invalid - contains emojiCustom Error Message
class Person < ApplicationRecord
validates :first_name, no_emoji: { message: "cannot contain emojis" }
end
NoEmojiAnywhereValidator - Validate all string/text columns
Automatically apply no-emoji validation to all string and text columns in your model:
class Person < ApplicationRecord
include EmojiValidator::NoEmojiAnywhereValidator
endperson = Person.new(first_name: "😃", last_name: "😃")
person.valid? # false
person.errors.count # 2 (errors on both first_name and last_name)Emoji Support
This gem uses the unicode-emoji gem which supports:
- Basic Emoji (😀, 🎉, etc.)
- Emoji with skin tones (👋🏽, etc.)
- Emoji sequences (flags, keycaps, ZWJ sequences)
- And more!
See the unicode-emoji documentation for more details.
License
Apache-2.0