+ Start a Discussion
mdangondmdangond 

Can I check for the existance of a value in the account name using a trigger?

In trying to enforce our account naming standard, I would like to write a trigger that checks for the existance of the "Billing City" in the new account name a user is trying to create. Our account naming convention is "Accout Name - Billing City", so my trigger needs to check for the existance of a hyphen (" - ") and Billing City in the name.

 

A correct account name would be: IBM - San Francisco or HP - San Diego.

 

Can this be done with a trigger?

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
jhenningjhenning
Yes, this is very easy to do. Here is one that could work for you. Enjoy!

trigger ValidateAccountName on Account (before insert, before update) { string strCompare = ' - '; List<Account> accounts = trigger.new; for (Account acct:accounts){ if (!acct.name.contains(strCompare)){ acct.name.addError('Account name must be in format: Company - Billing City'); } } }

 

All Answers

jhenningjhenning
Yes, this is very easy to do. Here is one that could work for you. Enjoy!

trigger ValidateAccountName on Account (before insert, before update) { string strCompare = ' - '; List<Account> accounts = trigger.new; for (Account acct:accounts){ if (!acct.name.contains(strCompare)){ acct.name.addError('Account name must be in format: Company - Billing City'); } } }

 

This was selected as the best answer
jhenningjhenning

Actually you could create a "Validation Rule" that does the same thing:

 

CONTAINS( Name , ' - ') = false

 

Validaton rules are easier to maintain than writing Apex code. But the choice is yours.

mdangondmdangond

This is perfect.

 

Thanks so much John!

mdangondmdangond
Thanks so much! I will use the validation rule you also gave me but this code will be very handy later on ....