[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 281
  • Last Modified:

date validation

I have a text field that takes date in the format MM/DD/YYYY. i did the validation for format. also it should make sure that entered date is after todays date or systems date.
how can i do that using javascript?

ALso i have two text fields to indicate the range of period like from_______ to _________

how can i validate that second date is alwas after first one??
0
soft_techy
Asked:
soft_techy
  • 4
1 Solution
 
kingsfan76Commented:
here's a function I used to find the difference in date

function dateDiff(strDate1,strDate2)
{
  datDate1= Date.parse(strDate1);
  datDate2= Date.parse(strDate2);
  return((datDate2-datDate1)/(24*60*60*1000));
}

this function should be used before the the date is validate to be valid
0
 
kingsfan76Commented:
here's a function I just wrote that will check if a date enter is valid for dates with MM/DD/YYYY format.  give it a try and see if it works for you  (of course you need to modify it slightly)

<script>
function CheckDate()
{
    var strDate = new String(myform.TheDate.value);
    var theDate = new Date(strDate);
    var today = new Date();
    if(isNaN(theDate))
    {
         alert("Date is invalid")
         return false;
     }
    else
    {
         var strTheDate = theDate.toString();
         var arrOriginalDate = strDate.split("/");
         theMonth = theDate.getMonth() + 1;
          if(theMonth != parseInt(arrOriginalDate[0]))
         {
              alert("Date is invalid");
              return false;
          }
       }
      
}
</script>

<form name="myform">
<input name="TheDate"><input type=button value="Check" onClick="CheckDate()">
</form>
0
 
kingsfan76Commented:
by combining the dateDiff() function with the CheckDate() function you should be able to accomplish what you need.

if you need help combining them to do what you need, please ask and i'll be glad to help.  :-)
0
 
kingsfan76Commented:
p.s. by combining i didn't mean to make those 2 functions into one.  I mean to write another function to call these two functions to work together, like:

call checkDate() to verify date is valid
if valid
call dateDiff to check if one date is greater than another (pass in current date as parameter if you need to check the date entered is greater than today's date)
0
 
soft_techyAuthor Commented:
It worked for me Thanks
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now