Trigger to restrict attachment size in Salesforce

trigger RestrictAttachmentTrigger on Attachment (before insert, before update) {
    for(Attachment attach : trigger.new) {
        if(attach.Body.size() > 3145728) {
            attach.addError('File size cannot be greater than 3 MB');
        } 
    }
}