junjizhi / junji-blog

My own blog
MIT License
0 stars 0 forks source link

Salesforce REGEX Validation Rule for Emojis #6

Open junjizhi opened 4 years ago

junjizhi commented 4 years ago

For a text field, we can't allow users to enter emojis in the text because that field is later ingested in a MySQL database doesn't have utf8mb4 support yet.

As a result, we need to add a validation rule to detect emoji and sends an error message.

I know the ruby regex for emoji is

/[\u{010000}-\u{10FFFF}]+/

Because Salesforce REGEX formula has escape and other quirks, it took me a while to compose the regex:

REGEX(My_Field__c, "[\\u010000-\\u10FFFF]+")

With this, you can compose your own validation rules.

For example, in my case, the final validation file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<ValidationRule xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>My_Field_Validation</fullName>
    <active>true</active>
    <description>Emoji is not supported in My_Field</description>
    <errorConditionFormula>AND(
      LEN (My_Field__c) &gt; 0,
      NOT(REGEX(My_Field__c, &quot;[\\u010000-\\u10FFFF]+&quot;))
    )
    </errorConditionFormula>
    <errorDisplayField>My_Field__c</errorDisplayField>
    <errorMessage>Emoji is not supported</errorMessage>
</ValidationRule>