Reputation: 925
I need to validate a date field which is being entered by a user via a visualforce page. The format my code expects is "yyyy-MM-dd".
What is the best way to handle this in apex. I have done similar stuff in Java before using certain standard classes which are not available in Apex like SimpleDateFormat for example.
Now I can check if the "format" is correct using a regular expression. But I must also prevent users from entering "9999-99-99" which satisfies the format. I am hoping Salesforce has a good built-in solution.
Thanks, Calvin
Upvotes: 1
Views: 17941
Reputation: 925
Guys I managed to solve my problem because it was a little unique anyways.
So I used a regex to validate the format of the date being entered to ensure it is in yyyy-MM-dd format.
The I used Date.valueOf
This built in method always takes a date in the form of yyyy-MM-dd. It throws an exception if that has a bad value like 9999-99-99 etc....I display the exception's message to the user using e.getMessage()
to complete my validation of the date fields.
Upvotes: 0
Reputation: 1214
You might try what I call control spoofing. I basically create an empty sObject that has a date field like a Task object (or something similarly light weight). On the screen I display the input for the task date which will render the native date field. Doing this you get salesforce to validate the date input from the user, and the user get's the nice calendar popup as well.
Here is a sample of what that would look like in the controller
public class MyController {
public Task DateInput {get;set;}
public MyController() {
DateInput = new Task();
}
public void save() {
Date dInputDate = DateInput.ActivityDate;
//Format Date
DateTime dtValue = DateTime.newInstance(dInputDate.year(), dInputDate.month(), dInputDate.day());
string sFormattedDate = dtValue.format('yyyy-MM-dd');
}
}
Here is what the Page would look like
<apex:page controller="MyController">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel for="inputDate" value="My Date"/>
<apex:inputField value="{!DateInput.ActivityDate}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
You notice the formatting that I did in the save method. You can't use format on Date but you can on DateTime so I just convert the Date to a DateTime and then use the format method to format my date.
Upvotes: 5