I have restricted the user to enter the space and size should be 20 digit, If some one can guide me to prevent the user to enter special character in apex..i am not able to find any solution to put this validation rule . kindly anyone from community can help me.

Code :-

private static Boolean test(Account cRecord, String rName){
    if(cRecord != null && rName != null && rName == scons.Acl) {
        if(cRecord.L_EI.length() != 20 || cRecord.L_EI.containsAny('')) {
            errorMessages.add('Errro message');
            currentRecord.addError(' Error');   
            return true; 
        return false;
    return false;

All Scenarios I have covered kindly help me to add the condition that If user entered any special character in above field then error message should be displayed.

1 Answer 1


You're on the right way, just put your code to the trigger on before insert, before update and the errors will appear while saving records:

Apex Trigger:

trigger AccountTrigger on Account (before insert, before update) {
    if (Trigger.isBefore) { 

Apex Class:

public with sharing class AccountTriggerHandler {
    public static void onBefore(List<Account> newAccounts) {
        for (Account account_i : newAccounts) {
            //add check here
            //if check is not passed, add error like this:
            //account_i.addError('AccountTrigger: field ... cannot have symbols ...');

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .