-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a5cfa62
commit 028ecab
Showing
3 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |