function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
shekhar 46shekhar 46 

why cant we use validation rule on deleting record

why cant we write validation rule on deleting record
Best Answer chosen by shekhar 46
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Shekhar,

Here is the simple example.

If the FirstName  of contact is "Primary" and Lastname is "Contact" then user should get an error while deletion of the contact.

Trigger:
trigger DeleteContact on Contact (before delete) {
    if(Trigger.isdelete && trigger.isbefore){
        
        DeleteContactHandler d= new DeleteContactHandler();
        d.deletecontact(Trigger.old);
    }
}

Handler:
 
public class DeleteContactHandler {

    public void deletecontact(List<Contact> conlist){
        for(Contact c: conlist){
            system.debug('contact'+c);
            SYSTEM.debug('NAME'+c.name);
            if(c.FirstName=='Primary' && c.LastName=='Contact' ){
                c.adderror('you cannot delete primary contact');
            }
        }
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,​​​​​​​

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Shekhar,

Validation rule will only fire while creation on updation of a record.  That is how it id designed by salesforce. If you need to write some validation on deletion  you may have to use trigger.


Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
shekhar 46shekhar 46
hi sai praveen , 
can u sharre some example of validaion on deletion using trigger
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Shekhar,

Here is the simple example.

If the FirstName  of contact is "Primary" and Lastname is "Contact" then user should get an error while deletion of the contact.

Trigger:
trigger DeleteContact on Contact (before delete) {
    if(Trigger.isdelete && trigger.isbefore){
        
        DeleteContactHandler d= new DeleteContactHandler();
        d.deletecontact(Trigger.old);
    }
}

Handler:
 
public class DeleteContactHandler {

    public void deletecontact(List<Contact> conlist){
        for(Contact c: conlist){
            system.debug('contact'+c);
            SYSTEM.debug('NAME'+c.name);
            if(c.FirstName=='Primary' && c.LastName=='Contact' ){
                c.adderror('you cannot delete primary contact');
            }
        }
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,​​​​​​​
This was selected as the best answer