I have created following validation rule, but struggling how to add to it to also allow blank (space) values.
AND(NOT(ISBLANK(field__c)),
OR( LEN(field__c) > 20, NOT(REGEX(field__c,"^[0-9]+$"))))
Given that this is a Text
type field (and not a TextArea
, TextArea (Long)
, or TextArea (Rich)
), you can define the max length as part of the field itself.
That'll give you an automatic error message (which I assume Salesforce has already translated/localized for other locales, if that's a concern) which is slightly less terrifying for users. Users' minds shut down at pretty much any error, but something like
System.DmlException: Update failed. First exception on row 0 with id 0013m0000383mtzAAA; first error: STRING_TOO_LONG, SLA Serial Number: data value too large: 1234567890123 (max length=11):
is better (in my opinion) than what you'd get with a validation rule
System.DmlException: Update failed. First exception on row 0 with id 0013m0000383mtzAAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, 10 chars or fewer: [SLASerialNumber__c]
Specifically, the actual error "String too long" appears sooner and is in all caps. I believe we're conditioned to pay more attention to all-caps things as well, so STRING_TOO_LONG
is better than FIELD_CUSTOM_VALIDATION_EXCEPTION
You also say that you want to allow people to submit data without needing to supply this ref number. So that means you can't have any validation rule that has an ISBLANK(field__c)
on its own.
Salesforce auto-trims leading and trailing whitespace from text fields. This is done before system validation (i.e. defining the max length as part of the field itself) and validation rules are run. So there is no need to handle the scenario where people are including whitespace before/after the ref number.
If you get a reference number that's length 20, and you get 100 whitespace after it, it'll get trimmed down to a length of 20 before you/Salesforce have a chance to object.
If the field contains only whitespace, then it all gets trimmed out and you end up with a blank text field (i.e. the value is null
)
Is if you want to ensure that this reference number is populated eventually.
Say, if this is generating a Case
in Salesforce, and you want to make sure the ref number is populated before the Case's Status
is "Closed".
Beyond that, a validation rule doesn't really make sense here.
REGEX(field__c,"^[0-9\s]+$")
NOT(REGEX(field__c,"^[0-9\s]{1,20}$"))
field__c
is a text field, you could enforce the field length restriction through the field metadata itself. Also, I can't recall if Salesforce auto-trims leading/trailing whitespace in text fields, but if they do then having only whitespace wouldn't be possible. Even if it is though, how would that be any different than allowing the field to be blank in the first place? Going into more detail about why you're implementing this validation rule (what business issue does this help you/your org solve?) may be more productive.