Skip to content

Commit

Permalink
add: validates emoji presence
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenxuanhung-rightsvn committed Nov 15, 2023
1 parent a5cfa62 commit 028ecab
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/emoji/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
require 'emoji/validator/version'
require 'emoji/validator/no_emoji_anywhere_validator'
require 'emoji/validator/no_emoji_validator'
require 'emoji/validator/emoji_validator'

module Emoji
# <tt>ActiveModel</tt> and <tt>ActiveRecord</tt> validators to prevent
Expand Down
27 changes: 27 additions & 0 deletions lib/emoji/validator/emoji_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# frozen_string_literal: true

module Emoji
module Validator
# Validate an attribute against emojis
#
# class Person < ApplicationRecord
# validates :first_name, emoji: true
# end
#
# person = Person.new(first_name: "😃", last_name: "")
# person.valid? #true
# person.first_name = ""
# person.valid? #false
#
class EmojiValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.nil?
return if value.match(Unicode::Emoji::REGEX_VALID).present?

record.errors.add(attribute, :no_emojis)
end
end
end
end

ActiveModel::Validations::EmojiValidator = Emoji::Validator::EmojiValidator
31 changes: 31 additions & 0 deletions spec/emoji/emoji_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# frozen_string_literal: true

require 'spec_helper'

class TestEmojiValidator
include ActiveModel::Model
validates :first_name, emoji: true
validates :last_name, emoji: true

attr_accessor :first_name, :last_name
end

RSpec.describe Emoji::Validator::EmojiValidator do
it 'ignore nil values' do
test_object = TestEmojiValidator.new(first_name: '😃', last_name: '😃')

expect(test_object.valid?).to eq(true)
end

it 'Validates fields that contain no emojis' do
test_object = TestEmojiValidator.new(first_name: '',
last_name: '')

expect(test_object.valid?).to eq(false)
expect(test_object.errors.count).to eq(2)
expect(test_object.errors.details[:first_name])
.to eq([{ error: :no_emojis }])
expect(test_object.errors.details[:last_name])
.to eq([{ error: :no_emojis }])
end
end

0 comments on commit 028ecab

Please sign in to comment.