A Rails engine that provides validators for emoji strings using the unicode-emoji gem.
Add this line to your application's Gemfile:
gem "emoji_validator"And then execute:
bundle installBy 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 emojisAllow 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 emojis (no text allowed):
class StickerSet < ApplicationRecord
validates :emojis, emoji: { allow_multiple: true }
endsticker.emojis = "😀😁🎉" # ✓ Valid
sticker.emojis = "😀" # ✓ Valid
sticker.emojis = "😀 Hello" # ✗ Invalid - has textAllow 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 emojiAllow empty strings or nil values:
class OptionalReaction < ApplicationRecord
validates :emoji, emoji: { allow_blank: true, allow_nil: true }
endclass Reaction < ApplicationRecord
validates :emoji, emoji: { message: "pick one emoji" }
endIn addition to requiring emojis, you can also validate that fields do not contain emojis.
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 emojiclass Person < ApplicationRecord
validates :first_name, no_emoji: { message: "cannot contain emojis" }
endAutomatically 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)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.
Apache-2.0