1

I have a datetime field ( thru date picker) in Visual force page , while on submitting the form , i receive the entered date in the Apex class for validation purpose. How to check whether the user has entered a date or some other text , How can i check this .

<apex:inputText id="moveindate" value="{!moveindate}" onclick="DatePicker.pickDate(false, this, true);" />

1

If you are using a input text try the code below, adjust your pattern matcher according to your desired format. Datepicker by default gives mm/dd/yyy hh:mm AM/PM.

This article will give your more insight on pattern matcher : http://salesforcesource.blogspot.com/2010/01/utilizing-apex-pattern-and-matcher.html

Page:

<apex:page controller="pattern_match">
<apex:pageMessages ></apex:pageMessages>
<apex:form >
<apex:inputText id="moveindate" value="{!moveindate}" onclick="DatePicker.pickDate(false, this, true);" />
<apex:commandButton value="check number" action="{!checkfornumber}"/>
</apex:form>
</apex:page>

Controller:

public class pattern_match {
    public string moveindate{get;set;}
    public String date_format{get;set;}
    public Pattern MyPattern  {get;set;}
    public pattern_match (){
        moveindate = '';
    }

    public pagereference checkfornumber(){
    MyPattern = Pattern.compile('(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d) ([0-1]?[0-9]|[2][0-3]):([0-5][0-9]) (AM|PM)');
    Matcher MyMatcher = MyPattern.matcher(moveindate);
        if(!MyMatcher.matches()){
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: valid string is mm/dd/yyyy hh:mm AM/PM.');
                    ApexPages.addMessage(myMsg);
        }
    return null;
    }
}
6

If you are using apex:inputField that is bound to a date-time field, you do not need to validate anything. The system will automatically validate the input for you based on the user's locale. Otherwise, if it is a normal text field, you should use DateTime.parse inside a try-catch block. If the date is invalid, you'll get an exception, if not, it is a valid date-time. The best part is, it automatically tries to validate the input based on the user's locale, so some users might use 'mm/dd/yyyy' or 'dd/mm/yyyy', or some other format (of course, you're using the date picker, so that should help), and the system will usually understand their intent.

2
  • sorry im using inputText Jul 31 '13 at 13:58
  • You can verify the input from inputText using the DateTime.parse function, then, as outlined in the answer.
    – sfdcfox
    Jul 31 '13 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.