Jump to content

Validate Past And Future Dates

Recommended Posts

Hi everyone,


I'd like to share this code, that validates if the entered date is correct.

Enter the name of your field instead of "myDate", enter the correct numbers for allowedDaysInPast  and allowedDaysInFuture variables, enter texts of your messages.

If you don't want to validate in past or in future you can delete the correspond block.

Then add a Header@Footer element, select the Footer element, click the Source button and enter the code.

function validate_dates()
var dateFieldName = "myDate";
var allowedDaysInPast = 1;
var deniedMessagePast = "The entered date cannot be earlier than yesterday";
var allowedDaysInFuture = 1;
var deniedMessageFuture = "The entered date cannot be later than tomorrow";

dateFieldName = "InsertRecord" + dateFieldName;

var entered_value = document.getElementById(dateFieldName).value;
var entered_date = new Date(entered_value);

//Start of Validating in past
var todayP = new Date();
var allowedDatePast = new Date(todayP.setDate(todayP.getDate() - allowedDaysInPast));
allowedDatePast = allowedDatePast.setHours(0,0,0,0);
if(entered_date < allowedDatePast)
      return false;
//Finish of validating in past

//Start of Validating in future
var todayF = new Date();
var allowedDateFuture = new Date(todayF.setDate(todayF.getDate() + allowedDaysInFuture));
allowedDateFuture = allowedDateFuture.setHours(23,59,59);
if(entered_date > allowedDateFuture)
      return false;
//Finish of validating in future


I'll be grateful, if you tell me if the code works or if any errors occur.

Have a nice day!

Link to comment
Share on other sites

  • 2 weeks later...
  • 7 years later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...