-1

I am very new to Javascript and am trying to ensure the date entered in a textbox (i haven't used number as im playing) is not less than todays date. I think I have over complicated this, please can you help me with the logic.

I start by reading user date and split user input into dd/mm/yyyy

//date regex ensures day and month != 00 && is a valid date

var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])
[\/\-]\d{4}$/;;  

//store user date
var readDate = document.getElementById("myDate").value;

//if date is valid

if(dateformat.test(readDate))
{           
    var day = splitDate[0];

    var month = splitDate[1];

    var year = splitDate[2];

    var dateToday = new Date()
    var dd = dateToday.getDate()
    var mm = dateToday.getMonth() + 1
    var yyyy = dateToday.getFullYear()

    console.log('date today is: ' + dd + '/' + mm + '/' + yyyy); 

    if(day > dd)
    {
        if(month >= mm)
        {
            if(year >= yyyy)
                {
                    console.log('it works - continue')
                    return true;
                }
            else
            {
                console.log('old year')
                return false;
            }
        }
        else
        {
            console.log('old month')
            return false;
        }
    }
    else
    {
            console.log('old day')
            return false;
    }
}
else
{
  console.log('invalid date')
}

I know this is very very dirty but I am so confused with the logic and before experts start using lambdas etc that i am not use too I just want to find out why this will not work? and how to get it to work? surely it is

I wrote this out to follow but it still does not help me

Date is valid when: User day > current day

   User month > = current month

   User year > = current year

Today’s date = 21/11/2017

So if user enters:

21/11/2017   not valid
02/03/2017  not valid
22/12/2017  valid 

but its not working

why oh why?

have i over complicated this?

it would be wonderful to know why it does not work in a very simple and easy way

thank you

p.s. if there is an easier way but keeping my dateformat, readDate and splitDate intact please can you help me find it? thanks

simon
  • 13
  • 4

3 Answers3

0

Use the moment well know library.

Here is an example :

PS: I have taken the start of the day as reference for the check.


// This is your user date
const readDate = '21/11/2017';

// We gives the date to moment library and ask if the date is ok
// For the library to know about which date structure to look for we tell it
if (!moment(readDate, 'DD/MM/YYYY').isValid()) {
  console.log('Wrong format!');
}

// We transform the date into a Timestamp
// (number of milisecond since st january 1970)
// In order to perform a comparaison with the timestamp of the start of the day
if (moment(readDate, 'DD/MM/YYYY').valueOf() >= moment().startOf('day').valueOf()) {
  console.log('Good');
} else {
  console.log('Bad');
}
<!DOCTYPE html>
<html>

<head>
  <!-- reference Moment.js library -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js" type="text/javascript"></script>
</head>

<body>

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • thanks but im looking for a JS solution as thats my learning point and trying to avoid other libraries...can you help? – simon Nov 21 '17 at 17:38
0

There is plenty of cleaner ways to check this for you but lets talk about your logic

You are nesting the month and year test inside the day test block so probably when you insert a date with a lower day value that today's it wont even test if the month/year values are greater that the today's value.

you could create a new date from your input:
let inputDate = new Date(year, month, day, 0, 0, 0, 0)
a new date from your today's date:
let todayDate = new Date(yyyy, mm, dd, 0, 0, 0, 0)
and compare:
if (inputDate > todayDate)

0

I have restructure your code. This may help you to get expected output.

$(function(){
   var dateFormat = /^(?:(?:31(\/)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/; //date formats /
   
   $("#check").on("click", function(){
     dateValidate(dateFormat);   
   });
   


});

function dateValidate(dateFormat){

  var readDate = document.getElementById("myDate").value;

  //if date is valid

  if(dateFormat.test(readDate))
  {     
    var splitDate = readDate.split("/");
    
    var day = splitDate[0];
    var month = splitDate[1];
    var year = splitDate[2];
    
    var dateToday = new Date();
    var dd = dateToday.getDate();
    var mm = dateToday.getMonth() + 1;
    var yyyy = dateToday.getFullYear();

    console.log('Date Today is: ' + dd + '/' + mm + '/' + yyyy); 

    if(day > dd)
    {
      if(month >= mm)
      {
        if(year >= yyyy)
          {
           console.log('it works - continue')
           return true;
          }
        else
        {
         console.log('Old Year');
         return false;
        }
      }
      else
      {
       console.log('Old Month');
       return false;
      }
    }
    else
    {
        console.log('Old Day')
        return false;
    }
  }
  else
  {
   console.log('Invalid Date');
   $("#myDate").focus();
   return false;
  }


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dateField">
 <input type="text" id="myDate" placeholder="dd/mm/yyyy"/>
 <button id="check">Check</button>
</div>
  • looks good but do I need this: ? how would you clean it up without using the nested if? is that even possible? ......like can I not use 1 if statement with >= && || conditions? – simon Nov 21 '17 at 18:13