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
Sai.MaharajpetSai.Maharajpet 

trigger to validate the age by using date of birth and add error message if age < 18 please help me in this thanks

trigger DateofBirth on Account (before insert) {
    for(Account a:trigger.new){
        if(a.Date_of_Birth__c!=NUll && ((system.today()- a.Date_of_Birth__c)/365 <=18)){
            a.Date_of_Birth__c.adderror('Age should be more than 18');
        }
    }
}

 

error i am facing:

Date expressions must use Integer or Long

Best Answer chosen by Sai.Maharajpet
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi Sai,
Use daysBetween() method of date class to find number of days between today and date of birth instead of subtraction.
Try this code
trigger DateofBirth on Account (before insert) {
    for(Account a:trigger.new){
        date dob = a.Date_of_Birth__c;
        Integer age = Integer.valueOf(dob.daysBetween(Date.Today()))/365;
        if(age<18){
            a.Date_of_Birth__c.adderror('Age should be more than 18');
        }
        
    }
}

Please refer below link which might help you in this
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_date.htm

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards

All Answers

Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi Sai,
Use daysBetween() method of date class to find number of days between today and date of birth instead of subtraction.
Try this code
trigger DateofBirth on Account (before insert) {
    for(Account a:trigger.new){
        date dob = a.Date_of_Birth__c;
        Integer age = Integer.valueOf(dob.daysBetween(Date.Today()))/365;
        if(age<18){
            a.Date_of_Birth__c.adderror('Age should be more than 18');
        }
        
    }
}

Please refer below link which might help you in this
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_date.htm

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards
This was selected as the best answer
Ankit Solanki 6Ankit Solanki 6
trigger DateofBirth on Account (before insert,before update) {   
    for(Account ac:trigger.new){
        Date a = Date.today();
        Date startDate = Date.valueOf(ac.birthdate__c);
        Integer numberDaysDue = integer.valueOf(startDate.daysBetween(a));
Integer age =  numberDaysDue/365;       
        if(age <= 18){
            system.debug('Test ::' + age);
            ac.addError('Age should be more than 18');
        }
    }
}
Sai.MaharajpetSai.Maharajpet
Thank you Devi Chandrika & Ankit Solanki for your quick response