Validation Rule not running the whole formula

regular-expressionsvalidation-rule

A field(Example__c, Text 255 char) can have a value of alphanumeric(numbers and/or letters) type and character length
should ONLY be either:

  1. 3 character value
  2. 7 character value
  3. 12 character value

I have written the below validation rule:

AND(
    NOT(
        REGEX(Example__c,"[A-Za-z0-9])
    ),
    OR(
        LEN(Example__c) <> 3,
        LEN(Example__c) <> 7,
        LEN(Example__c) <> 12
    )
)

However while testing I see that although it's checking the alphanumeric validation but it's not checking the length at all. All values are getting saved no matter what the length is. I am unable to find what mistake I have made in the formula, please help.

Best Answer

The correct version of the validation rule in your question is :

AND(
    NOT(
        REGEX(Example__c, "[A-Za-z0-9]")
    ),
    OR(
        LEN(Example__c) <> 3,
        LEN(Example__c) <> 7,
        LEN(Example__c) <> 12
    )
)

Notice the " at the end of Regex and an extra ) removed.

But I think for the requirement which is described , we need to have OR operator instead of outermost AND. This is because error needs to be thrown if either the field does not match the regex or its length is not valid. Also , the length check needs to be an AND. Based on above logic , validation rule becomes :

OR(
    NOT(
        REGEX(Example__c, "[A-Za-z0-9]")
    ),
    AND(
        LEN(Example__c) <> 3,
        LEN(Example__c) <> 7,
        LEN(Example__c) <> 12
    )
)
Related Topic