-1

I am trying to create a validation rule for a text field to only allow letters and a few special characters to be saved in the field. The special characters are " - ", " . "," - ".

This is the rule I have so far.

not(REGEX( Test_Validation_Rule_Field__c , "[a-zA-Z0-9- \.\,\- ]+"))

My issue currently that is impeding me from finishing the rest is now the field will not save when I try to clear the field. It makes it required after initially saving a field, which isn't the the greatest UX.

2 Answers 2

2

Validation rules fire when the result of the formula is true. So you'll need to add something to your validation rule to allow blank as a valid value.

This could be as simple as changing the + in your regex, which denotes "1 or more of these things",
to *, which denotes "any number, including 0 of these things"

While that should be perfectly understandable by people with a working knowledge of regex, it wouldn't be obvious to laypeople. An alternate approach would be to add in a NOT(ISBLANK(<your field here>)) and AND() those two conditions together.

e.g.

/* Only returns true if all of the conditions inside are true */
/* So the field being blank is enough to get you out of the validation */
/* Blank check first to take advantage of short-circuit evaluation */
AND(
    NOT(ISBLANK(<your field here>)),
    <existing statement with the regex>
)

Having the blank check be explicit should make it easier for others to reason about (if that is a concern).

0

You can use an "if" statement in your validation rule, to evaluate the rule only if the field is not blank

as such:

IF(NOT(ISBLANK(your_field__c)), (your regex expression), false)

this will make sure, your validation rule is trigged only when the field is not blank.

2
  • 1
    Generally speaking, using IF() to return a true/false value is a bit of a red flag. It'd work just fine, but extra typing means extra chances to make mistakes. IF(<condition>, true, false) simplifies to just <condition>. In this scenario, it would simplify down to AND(<not blank check>, <regex>).
    – Derek F
    Commented Feb 5 at 16:37
  • Yes I agree, using AND (as per your answer) is a better approach, as we don't need the false evaluation in the IF statement. I just posted this answer, as I tried doing it using IF approach and it worked. Posted the answer just to show that it could be achieved this way too. Thanks for your valuable feedback, appreciate it!
    – prem22
    Commented Feb 5 at 16:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .