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
IntroAmmyIntroAmmy 

Need to add condition if birthdate is less than 18 years

How can i throw error msg via apex if i have a field name birthdate in vf page and if birthdate is less than 18 years it throw error while i am saving record ..
Can somenone please help.

Thanks,
 
Best Answer chosen by IntroAmmy
Malika Pathak 9Malika Pathak 9
Hi Amit,

Greetings!

Apex:-
if (birthdate  < 18)
{
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Your Error Message'));
    return null;
}
 
Vf Page- 
add this tag in VF Code
<apex:pageMessages ></apex:pageMessages>

Please mark it as the best answer if it helps you to fix the issue.

Thank you!

Regards,
Malika Pathak

All Answers

AnudeepAnudeep (Salesforce Developers) 
Hi Amit, 

You can add the error message using addError in the apex trigger

A simple example for addError is 
 
trigger blockAccounts on Account (before insert) {
    for(Account record:trigger.new) {
        if(record.name=='Blocked') {
            record.name.addError('This name is not allowed');
        }
    }
}

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
Malika Pathak 9Malika Pathak 9
Hi Amit,

Greetings!

Apex:-
if (birthdate  < 18)
{
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Your Error Message'));
    return null;
}
 
Vf Page- 
add this tag in VF Code
<apex:pageMessages ></apex:pageMessages>

Please mark it as the best answer if it helps you to fix the issue.

Thank you!

Regards,
Malika Pathak
This was selected as the best answer
IntroAmmyIntroAmmy
By the way can we make our custom VF page responsive so that it can open in mobile as well ?
Please let me know if any idea how we can do that.