[SalesForce] Validation rule to allow 15 digits only

Please advise a validation rule to allow me to enter 15 digits only.

If the number of entered digits is higher or less than 15 the validation rule should display an error message.

If there are spaces, special characters and letters entered in the field the validation rule should display an error message.

The validation should allow only 15 digit numbers to be entered into the field.

So far I used the following:

OR(

AND(
LEN(custom_text_field__c) = 15,
NOT(REGEX(custom_text_field__c,"^[0-9]+$"))
),

AND(
LEN(custom_text_field__c) <> 15,
REGEX(custom_text_field__c,"^[0-9]+$")
)

)

However it is not working when there is a space between the digits.
I'm still able to save the record without being stopped by the validation rule. Even with the following: "123 4567 89012345 1234 5678 9012345" the validation rule does not display and error message. Please advise how to include the spaces in the regex so that the validation rule to be triggered every time there is a space amidst the digits.

Best Answer

The logic is over-complicated; the second regex returns false when there are only numbers, but you actually wanted it to return true regardless. You can simplify this formula to:

OR( LEN(custom_text_field__c) <> 15, NOT(REGEX(custom_text_field__c,"^[0-9]+$")))

If you want to allow blank values, you need to add that in, too:

AND(NOT(ISBLANK(custom_text_field__c)),
OR( LEN(custom_text_field__c) <> 15, NOT(REGEX(custom_text_field__c,"^[0-9]+$"))))
Related Topic