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
Harjeet SinghHarjeet Singh 

How to put a validation on date picker field in visual force page(selected date must not be a past date)

Hi All,
I have a requiremnt that an user cant select a date of past in date picker list in visual force page and if he selects/enters a date of past an error msg should be displayed.
Note:This date field on Vf page is a dummy field and is not present on object level.
I am attaching my Vf code and controller along with my screen shot.
public class HarjeetWrapper{
             private Set<Id> selectedContactIds;
             public String selectedActions{get;set;}
             public Date dat {get;set;}
              

            


            public ApexPages.StandardSetController setCon {
            get {
                if(setCon == null) {
                    setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select Id, Name,csord__Status__c, csord__Account__c from csord__Subscription__c where csord__Account__c=:accountid ]));
                             }
                            setCon.setPageSize(20);
                        return setCon;
                }
        set;
    }
    public List<csord__Subscription__c > getWrapSubscriptionList() {
         
         // setCon.setpagesize(20);
         setCon.setpageNumber(1);
         return (List<csord__Subscription__c >) setCon.getRecords();
    }
    public Integer getPageNumber(){
 
        return this.setCon.getPageNumber();
 
    }
    

 


   Public Integer getTotalPages(){
 
        Decimal totalSize = this.setCon.getResultSize();
        Decimal pageSize = this.setCon.getPageSize();
 
        Decimal pages = totalSize/pageSize;
 
        return (Integer)pages.round(System.RoundingMode.CEILING);
     }
 

    //Our collection of the class/wrapper objects wrapAccount
    public List<wrapSubscription> wrapSubscriptionList {get; set;}
    public List<csord__Subscription__c> selectedSubscriptions{get;set;}
    public Boolean isCancel{get;set;}
    public string accountid;
    
    
    public HarjeetWrapper(){
      accountid=ApexPages.currentPage().getParameters().get('id');
        if(wrapSubscriptionList == null) {
           wrapSubscriptionList= new List<wrapSubscription>();
            for(csord__Subscription__c s: [select Id, Name,csord__Status__c, csord__Account__c from csord__Subscription__c where csord__Account__c=:accountid ]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapSubscriptionList.add(new wrapSubscription(s));
            }
        }
    }
    
    
    public void processSelected() {
    selectedSubscriptions = new List<csord__Subscription__c>();
 
        for(wrapSubscription wrapSubscriptionObj : wrapSubscriptionList) {
            if(wrapSubscriptionObj.selected == true) {
                selectedSubscriptions.add(wrapSubscriptionObj.sub);
            }
        }
    }
    
    public PageReference cancel(){
        return new PageReference('/'+accountid);
    }
    
    public void next(){

    if(this.setCon.getHasNext())
        this.setCon.next();

}

 public void previous(){

    if(this.setCon.getHasPrevious())
        this.setCon.previous();

}
        public List<SelectOption> getCountriesOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('Take Over','Take Over'));
        countryOptions.add(new SelectOption('Invoice Switch','Invoice Switch'));
        countryOptions.add(new SelectOption('Move','Move'));
        /*countryOptions.add(new SelectOption('Germany','Germany'));
        countryOptions.add(new SelectOption('Ireland','Ireland'));*/
 
        return countryOptions;
}




                         
 
    // This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapSubscription {
        public csord__Subscription__c sub {get; set;}
        public Boolean selected {get; set;}
 
        public wrapSubscription(csord__Subscription__c s) {
            sub = s;
            selected = false;
        }
    }
}
<apex:page docType="html-5.0" controller="HarjeetWrapper" sidebar="false" showHeader="false">



    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
        <apex:pageBlockSection >
        <apex:pageBlockSectionItem >
        <!-- <apex:outputText value="{!selectedActions}" label="You have selected:"/>-->
        <!--<apex:outputText label="Select the Action:"/>-->
        Select the Action:
        <!--<apex:outputPanel>-->
          <apex:selectList value="{!selectedActions}" multiselect="false" size="1">
                <apex:selectOption itemValue="Take Over" itemLabel="Take Over"/>
                <apex:selectOption itemValue="Invoice Switch" itemLabel="Invoice Switch"/>
                <apex:selectOption itemValue="Move" itemLabel="Move"/>
            </apex:selectList>
            <!--</apex:outputPanel>-->
            </apex:pageBlockSectionItem>
           </apex:pageBlockSection> 
           <apex:PageBlockSection >
            <apex:pageBlockSectionItem >
                Date: <apex:input type="date" value="{!dat}" required="true" />
             </apex:pageBlockSectionItem>
            <!--<apex:input value="{!myDate}" id="theTextInput" type="date"/>-->
        </apex:pageBlockSection>
    </apex:pageBlock>
 
    
        <apex:pageBlock title="Select Subscription"  >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Proceed " action="{!processSelected}" />
                <apex:commandButton value="Cancel" action="{!cancel}" immediate="true" />
            </apex:pageBlockButtons>
       <apex:pageblockSection title="Subscriptions" collapsible="false" columns="1" >
             <apex:pageBlockTable value="{!wrapSubscriptionList}" var="subWrap">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')" />
                        </apex:facet>
                        <!--<apex:inputCheckbox value="{!subWrap.selected}" id="inputId"/>-->
                                <apex:inputCheckbox value="{!subWrap.selected}" id="inputId" disabled="{!NOT(subWrap.sub.csord__Status__c=='Active')}" />
                    </apex:column>
                    
                    <!--<apex:column value="{!subWrap.sub.Name}" />-->
                    <apex:column headerValue="Subscription Name" > 
                        <!--<apex:commandLink value="{!subWrap.sub.Name}" action="/{!subWrap.sub.Id}"/>-->
                       <apex:outputLink value="/{!subWrap.sub.Id}" target="_blank"> {!subWrap.sub.Name} </apex:outputLink>
                   </apex:column>
                     <apex:column value="{!subWrap.sub.csord__Status__c}" />
                    <apex:column value="{!subWrap.sub.csord__Account__c}" />
                </apex:pageBlockTable>
                </apex:pageblockSection>
             <apex:commandButton rendered="{!setCon.hasPrevious}" value="first" action="{!setCon.first}"/>
            <apex:commandButton rendered="{!setCon.hasPrevious}" value="Previous" action="{!setCon.previous}"/>
            <apex:outputLabel value=" (page {!pageNumber} of {!totalPages})"/>
            <apex:outputText rendered="{!(setCon.pageNumber * setCon.pageSize) < setCon.ResultSize}" value="{!setCon.pageNumber * setCon.pageSize} Of {!setCon.ResultSize}"></apex:outputText>
            <apex:outputText rendered="{!(setCon.pageNumber * setCon.pageSize) >= setCon.ResultSize}" value="{!setCon.ResultSize} Of {!setCon.ResultSize}"></apex:outputText>
            <apex:commandButton rendered="{!setCon.hasNext}" value="next" action="{!setCon.next}"/>
            <apex:commandButton rendered="{!setCon.hasNext}" value="last" action="{!setCon.last}"/>

     <apex:pageBlock />
                
                
                <apex:pageblockSection title="Selected Subscriptions" collapsible="false" columns="1" >
                   <apex:pageBlockTable value="{!selectedSubscriptions}" var="c" id="table2" title="Selected Subscriptions" width="100%">
                    <!--<apex:column value="{!c.Name}" headerValue="Subscription Name"/>-->
                    <apex:column headerValue="Subscription Name" > 
                        <apex:commandLink value="{!c.Name}" action="/{!c.Id}" target="_blank"/> 
                      </apex:column> 
                    <apex:column value="{!c.csord__Status__c}" headerValue="Status"/>
                    <apex:column value="{!c.csord__Account__c}" headerValue="Account"/>
                </apex:pageBlockTable>
            

            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
 
</apex:page>
screen shot
Please help me out in this situation,i really need to solve this as soon as possible.
Many thanks in advance.
Note:Pls dont suggest/refer a link to me for this as i have gone through so many links but no luck.So pls look into my code which i have posted here and modify that accordingly.I am seeking help from last 4 days in this forum.



 
Best Answer chosen by Harjeet Singh
Madhanprabhu Thangadurai 1Madhanprabhu Thangadurai 1
Oh!! No.. i'm sorry. Please remove format() in the below method. If you use format() it will convert the Date into String.
 
public String DateValidate()
{
Date todayDate = date.today();
if (todayDate > dat) {
    dateError = 'Invalid date';
}
return dateError;
}

All Answers

Madhanprabhu Thangadurai 1Madhanprabhu Thangadurai 1
Hi Harjeet Singh,

Create a Div element below to your Date field.
<div class="errorMsg"><strong></strong>&nbsp;{!dateError}</div>
Use "onchange" attribute in your Date field component and call the following javascript method which will call your Apex method.
 
function callDateValidate()
{
HarjeetWrapper.DateValidate();
}
public String dateError {get;set;}
public String DateValidate()
{
Date todayDate = date.today().format();
if (todayDate > dat) {
    dateError = "Set the error Message Here"
}
return dateError;
}

Reference:

http://salesforce.stackexchange.com/questions/47993/how-to-show-the-validation-error-below-the-input-field-in-vf-page
Harjeet SinghHarjeet Singh
Dear Madhanprabhu,
many thanks for your response.but still my functionality is not working moreover it is not saving th ecode at all,while saving i am getting "Error:HarjeetWrapper Compile Error: Illegal assignment from String to Date at line 59 column 1".
However i am posting my code here so that you can get better idea where and what is the error coming now.
public class HarjeetWrapper{
             private Set<Id> selectedContactIds;
             public String selectedActions{get;set;}
             public Date dat {get;set;}
              

            


            public ApexPages.StandardSetController setCon {
            get {
                if(setCon == null) {
                    setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select Id, Name,csord__Status__c, csord__Account__c from csord__Subscription__c where csord__Account__c=:accountid ]));
                             }
                            setCon.setPageSize(20);
                        return setCon;
                }
        set;
    }
    public List<csord__Subscription__c > getWrapSubscriptionList() {
         
         // setCon.setpagesize(20);
         setCon.setpageNumber(1);
         return (List<csord__Subscription__c >) setCon.getRecords();
    }
    public Integer getPageNumber(){
 
        return this.setCon.getPageNumber();
 
    }
    

 


   Public Integer getTotalPages(){
 
        Decimal totalSize = this.setCon.getResultSize();
        Decimal pageSize = this.setCon.getPageSize();
 
        Decimal pages = totalSize/pageSize;
 
        return (Integer)pages.round(System.RoundingMode.CEILING);
     }
 

    //Our collection of the class/wrapper objects wrapAccount
    public List<wrapSubscription> wrapSubscriptionList {get; set;}
    public List<csord__Subscription__c> selectedSubscriptions{get;set;}
    public Boolean isCancel{get;set;}
    public string accountid;
    
    
    public HarjeetWrapper(){
      accountid=ApexPages.currentPage().getParameters().get('id');
        if(wrapSubscriptionList == null) {
           wrapSubscriptionList= new List<wrapSubscription>();
            for(csord__Subscription__c s: [select Id, Name,csord__Status__c, csord__Account__c from csord__Subscription__c where csord__Account__c=:accountid ]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapSubscriptionList.add(new wrapSubscription(s));
            }
        }
    }
    
    
    public void processSelected() {
    selectedSubscriptions = new List<csord__Subscription__c>();
 
        for(wrapSubscription wrapSubscriptionObj : wrapSubscriptionList) {
            if(wrapSubscriptionObj.selected == true) {
                selectedSubscriptions.add(wrapSubscriptionObj.sub);
            }
        }
    }
    
    public PageReference cancel(){
        return new PageReference('/'+accountid);
    }
    
    public void next(){

    if(this.setCon.getHasNext())
        this.setCon.next();

}

 public void previous(){

    if(this.setCon.getHasPrevious())
        this.setCon.previous();

}
        public List<SelectOption> getCountriesOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('Take Over','Take Over'));
        countryOptions.add(new SelectOption('Invoice Switch','Invoice Switch'));
        countryOptions.add(new SelectOption('Move','Move'));
        /*countryOptions.add(new SelectOption('Germany','Germany'));
        countryOptions.add(new SelectOption('Ireland','Ireland'));*/
 
        return countryOptions;
}

public String DateValidate()
{
Date todayDate = date.today().format();
if (todayDate > dat) {
    dateError = 'Invalid date';
}
return dateError;
}



                         
 
    // This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapSubscription {
        public csord__Subscription__c sub {get; set;}
        public Boolean selected {get; set;}
 
        public wrapSubscription(csord__Subscription__c s) {
            sub = s;
            selected = false;
        }
    }
}
 
<apex:page docType="html-5.0" controller="HarjeetWrapper" sidebar="false" showHeader="false">



    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
        <apex:pageBlockSection >
        <apex:pageBlockSectionItem >
        <!-- <apex:outputText value="{!selectedActions}" label="You have selected:"/>-->
        <!--<apex:outputText label="Select the Action:"/>-->
        Select the Action:
        <!--<apex:outputPanel>-->
          <apex:selectList value="{!selectedActions}" multiselect="false" size="1">
                <apex:selectOption itemValue="Take Over" itemLabel="Take Over"/>
                <apex:selectOption itemValue="Invoice Switch" itemLabel="Invoice Switch"/>
                <apex:selectOption itemValue="Move" itemLabel="Move"/>
            </apex:selectList>
            <!--</apex:outputPanel>-->
            </apex:pageBlockSectionItem>
           </apex:pageBlockSection> 
           <apex:PageBlockSection >
            <apex:pageBlockSectionItem >
                Date: <apex:input type="date" value="{!dat}" required="true" onchange="callDateValidate" />
				 <div class="errorMsg"><strong></strong>&nbsp;{!dateError}</div>
             </apex:pageBlockSectionItem>
            <!--<apex:input value="{!myDate}" id="theTextInput" type="date"/>-->
        </apex:pageBlockSection>
    </apex:pageBlock>
 
    
        <apex:pageBlock title="Select Subscription"  >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Proceed " action="{!processSelected}" />
                <apex:commandButton value="Cancel" action="{!cancel}" immediate="true" />
            </apex:pageBlockButtons>
       <apex:pageblockSection title="Subscriptions" collapsible="false" columns="1" >
             <apex:pageBlockTable value="{!wrapSubscriptionList}" var="subWrap">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')" />
                        </apex:facet>
                        <!--<apex:inputCheckbox value="{!subWrap.selected}" id="inputId"/>-->
                                <apex:inputCheckbox value="{!subWrap.selected}" id="inputId" disabled="{!NOT(subWrap.sub.csord__Status__c=='Active')}" />
                    </apex:column>
                    
                    <!--<apex:column value="{!subWrap.sub.Name}" />-->
                    <apex:column headerValue="Subscription Name" > 
                        <!--<apex:commandLink value="{!subWrap.sub.Name}" action="/{!subWrap.sub.Id}"/>-->
                       <apex:outputLink value="/{!subWrap.sub.Id}" target="_blank"> {!subWrap.sub.Name} </apex:outputLink>
                   </apex:column>
                     <apex:column value="{!subWrap.sub.csord__Status__c}" />
                    <apex:column value="{!subWrap.sub.csord__Account__c}" />
                </apex:pageBlockTable>
                </apex:pageblockSection>
             <apex:commandButton rendered="{!setCon.hasPrevious}" value="first" action="{!setCon.first}"/>
            <apex:commandButton rendered="{!setCon.hasPrevious}" value="Previous" action="{!setCon.previous}"/>
            <apex:outputLabel value=" (page {!pageNumber} of {!totalPages})"/>
            <apex:outputText rendered="{!(setCon.pageNumber * setCon.pageSize) < setCon.ResultSize}" value="{!setCon.pageNumber * setCon.pageSize} Of {!setCon.ResultSize}"></apex:outputText>
            <apex:outputText rendered="{!(setCon.pageNumber * setCon.pageSize) >= setCon.ResultSize}" value="{!setCon.ResultSize} Of {!setCon.ResultSize}"></apex:outputText>
            <apex:commandButton rendered="{!setCon.hasNext}" value="next" action="{!setCon.next}"/>
            <apex:commandButton rendered="{!setCon.hasNext}" value="last" action="{!setCon.last}"/>

     <apex:pageBlock />
                
                
                <apex:pageblockSection title="Selected Subscriptions" collapsible="false" columns="1" >
                   <apex:pageBlockTable value="{!selectedSubscriptions}" var="c" id="table2" title="Selected Subscriptions" width="100%">
                    <!--<apex:column value="{!c.Name}" headerValue="Subscription Name"/>-->
                    <apex:column headerValue="Subscription Name" > 
                        <apex:commandLink value="{!c.Name}" action="/{!c.Id}" target="_blank"/> 
                      </apex:column> 
                    <apex:column value="{!c.csord__Status__c}" headerValue="Status"/>
                    <apex:column value="{!c.csord__Account__c}" headerValue="Account"/>
                </apex:pageBlockTable>
            

            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
	<script>    
function callDateValidate()
{
HarjeetWrapper.DateValidate();
}
</script>
 
</apex:page>
error is showing at "Date todayDate = date.today().format();" line in controller in new method which i put after your comments.
Please look into it and i hope this time you will come up with a perfect solution.
Mnay thanks in advance.
 
Madhanprabhu Thangadurai 1Madhanprabhu Thangadurai 1
You missed the following declaration in your Controller.
public String dateError {get;set;}

 
Harjeet SinghHarjeet Singh
Dear Madhanprabhu,
I have declared that said variable in the controller then also i am getting the same error.
Madhanprabhu Thangadurai 1Madhanprabhu Thangadurai 1
Oh!! No.. i'm sorry. Please remove format() in the below method. If you use format() it will convert the Date into String.
 
public String DateValidate()
{
Date todayDate = date.today();
if (todayDate > dat) {
    dateError = 'Invalid date';
}
return dateError;
}
This was selected as the best answer
Harjeet SinghHarjeet Singh
Thanks for your input.
I have a question here,currently it is showing date format in mm/dd/yyyy but what if an user wants it in dd/mm/yyyy.
Please provide your inputs on it.

Mnay thanks in advance