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.

<SCRIPT LANGUAGE="JavaScript">
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)
   {
      alert(deniedMessagePast);
      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)
   {
      alert(deniedMessageFuture);
      return false;
   }
//Finish of validating in future
}

document.getElementById("caspioform").onsubmit=validate_dates;
</SCRIPT>

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.

Guest
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.

Loading...
×
×
  • Create New...