[SalesForce] Required field validation rule for [Billing|Shipping]StateCode with State & Country picklists enabled

When using State & Country picklist functionality, is it possible to write a Validation Rule that targets the Billing State or Shipping State fields to make them required but only when the Country has States?

Since some Countries do not have States/Regions and this is a restricted picklist field, Salesforce prevents bad data at the database level as well as in the native UI. A Country with no States will always have a blank value in the State field(s).

So, for a Country which doesn't have any States configured, and therefore will accept no data in the Billing State or Shipping State address fields, what is the appropriate way to write the Validation Rule?

My functional requirement:

  • If the Country has States and BillingStateCode is blank, display
    error.
  • If the Country does not have States, BillingStateCode can (and
    must) be blank.

Best Answer

I would think you could implement the following validation rule on State:

AND(
    ISPICKVAL(State, ''),
    OR(
        ISPICKVAL(Country, 'CountryWithStates1'),
        ISPICKVAL(Country, 'CountryWithStates2'),
        ISPICKVAL(Country, 'CountryWithStates3')
    )
)

You'll have to manage the OR list yourself, but that seems tolerable.

If you would like to try a more programmatic approach, check out this blog post. It would allow you to write a trigger based validation something like:

Map<String, List<String>> countryToStates = GetDependentOptions('Lead', 'Country', 'State');
for (Lead newLead : newLeads)
{
    if (countryToStates.containsKey(newLead.Country) &&
        !countryToStates.get(newLead.Country).isEmpty() &&
        newLead.State == null)
    {
        newLead.State.addError(Label.State_Required);
    }
}