Before going to make it more complex, what do you think is it possible for you to bound your date variable with object so we can use <apex:inputField>
, by that manner VF itself take care of validation and all. '
If your above answer is NOT, then let's get into hard part. If you really want the same look and feel, which you seen with the default VF datepicker then there are some tricky ways (which I would personally not recommended because it is dirty way, but if you are ok with that and if you believe if will works for your requirement then you can go ahead), here I'm attaching code reference (Refer method 2) :
http://www.infallibletechie.com/2012/11/date-picker-in-visualforce-page.html
The recommended way to use datepicker with your page is, create a html 5 date input with <apex:input type="date">
, but it will render the browser based HTML5 Date picker, which is vary as per browser, to overcome that thing and make it more appropriate you can use any third party datepicker JS library like jQuery UI Datepicker or if your page using bootstrap framework then Bootstrap Datepicker. some of the datepicker library comes with prebuilt validation also, which you can use directly. otherwise you can create your own custom code for validation:
If you want to use custom JS for check date validation on page side, refer below JS code, you can modify the code as per your validation (I've used pure JS): you can modify it as per your need.
// Check Date for MM-DD-YYYY format
function isValidDate(subject){
if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
return true;
}else{
return false;
}
}
// Call function isValidDate('01-15-2016') returns true
By above function you can validate the date otherwise there is one more way by which you can do the validation that is on Controller side, just pass that value into a date variable and if error comes, send the error to page.
<input type="text"
?