We can use Mask plugin of jQuery for Datefield as $(txtBox).setMask(“19/39/9999”) which will accept inputs in mm/dd/yyyy format.
While using this we may face problems if it accepts invalid values like : Month value > 12, date value > 31 and also future dates.
The solution to this is after giving the date value in Textbox, we need to check whether the date is in correct format or not and if it is taking future dates.
We can use the following function by passing the Textbox value and the format of Date (“mm/dd/yyyy” or “dd/mm/yyyy” etc.), it will check whether the date given is valid date or Not.
E.g . Call the IsValidaDate() function by passing the textbox value and format of date like :- IsValidDate($txtBox.val(), ‘mm/dd/yyyy’);
function IsValidDate(dateString, dateFormat) { var days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var year, month, day, dateParts = null; var returnValue = false; //array of decission tree which will contain different format of Date var decisionTree = { 'm/d/y':{ 're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/, 'month': 1,'day': 2, year: 3 }, 'mm/dd/yy':{ 're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/, 'month': 1,'day': 2, year: 3 }, 'mm/dd/yyyy':{ 're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/, 'month': 1,'day': 2, year: 3 }, 'y/m/d':{ 're':/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/, 'month': 2,'day': 3, year: 1 }, 'yy/mm/dd':{ 're':/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/, 'month': 2,'day': 3, year: 1 }, 'yyyy/mm/dd':{ 're':/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/, 'month': 2,'day': 3, year: 1 } }; //Check whether the given date format is present or not in Decission tree var testDate = decisionTree[dateFormat]; //If textDate is there then get the Day, month and year of given Date if (testDate) { //get the Regular expression for the given date format dateParts = dateString.match(testDate.re); if (dateParts) { year = dateParts [testDate.year]; month = dateParts [test.month]; day = dateParts [testDate.day]; //Calculate the Number Of days in a month depending upon the year testDate= ((month == 2 && isLeapYear() && 29 )|| days[parseInt(month,10)] || 0); returnValue = 1