Skip to main content

Hi all,

I am trying to build a validation rule with REGEX for the field Phone. The validation rule should check the following:

  • Allow: Numbers
  • Allow: Characters such as '+', spaces, parenthesis '(', ')', '/', '-'
  • Allow: Character '+' should be only at the beginning of the phone number not in the middle or at the end

So, just searching pages with REGEX tutorials but unfortunately I could not find any appropriate in order to also decrypt the following expression literally:

 

NOT(REGEX(Phone,"(\\D?[0-9]{3}\\D?)[\\s][0-9]{3}-[0-9]{4}

")

)

 

No idea what do the following do?:

 

  • \\D? (at the beginning and at the end)
  • {3}
  • \\s
  • {4}

I would appreciate if experts in REGEX could give me some guidance here. 

 

#REGEX  #Salesforce Developer  #Sales Cloud  #Service Cloud  #Nonprofit  #Automation  #Integration

34 Antworten
  1. 14. Sept. 2021, 13:36

    Hi Laura,

     

    I guess I'll join the free-for-all to get best answer on this thread :)

     

    First of all, here is a regex that might be what you need:

    NOT(REGEX(Phone, "[+]{0,1}[-\\s\\.\\/0-9()]+"))

     

    Now I'll explain what the various parts of it do:

    [+]{0,1} means the character + can appear between 0 and 1 times. Because it's in the beginning of this expression, this character is only accepted at the beginning of the text we're matching.

     

    [-\\s\\.\\/0-9()]+ means that any of the characters inside the square brackets (will detail in a bit) are allowed any number of times (but must appear at least once). The + just after the closing bracket means "at least once".

     

    Now as for the specific characters here:

    - means the literal hyphen character

    \s means a whitespace character

    \. means a literal dot/period

    \/ means the literal character slash

    0-9 means any digit between 0 and 9

    () means closing or opening brackets

     

    Oh, and to cover the elements in your original regex, I can explain those as well:

    \D means any digit (same as 0-9)

    {3} and {4} mean that the preceding block has to appear exactly 3 or 4 times, respectively.

     

    You will notice that in this regex we actually use a double backslash \\ instead of a single one. This is actually not part of the Regex - it's for Salesforce to understand we mean a literal backslash and not a special character (like a tab \t or a line break \n). So we're actually double-encoding the expression, once for Salesforce, and a second time for the Regex engine.

     

    One of my favourite tools for writing and examining regular expressions is Regex101. You can try this one here. You can hover over the various elements of the expression to see what they mean, and see the results in real time.

0/9000