0

I have these two var's curdate and sdate...sdate is a standard string that someone enters and then it compares to curdate. curdate is a date field from a smarty template(to show today's date in mm/dd/yyyy format)

I need to convert sdate to the same type format before comparing it to curdate so someone doesn't enter something like jan/12/2013...it wont match and will show them this message.

if(sdate > curdate){
    var d= confirm("The date you selected: " + sdate + " is in the future, OK to continue?");
    if(!d) return false;
}
Shikiryu
  • 10,180
  • 8
  • 49
  • 75
Lynx
  • 1,462
  • 5
  • 32
  • 59

3 Answers3

1

You can "restrict" what the client input will be using JavaScript, to make sure that the data being entered is numeric, for example. With that numeric input, you can quite easily build a string in the desired format.
I've set up this fiddle, with, pretty much, the same code, as the one below. the fiddle also does some basic checks (like not accepting dates à la 33/54/1001), and parses the Date, too. As soon as a full date is entered, click the button and check the output in your console: it's a regular date object, which can be compared to another date object (like that of today: curdate = new Date();).
But in order for you to get started, here's a simplified version of the keypress handler, that deals with user input:

var keypress = function(e)
{
    e = e || window.event;//FROM HERE
    var el = e.target || e.srcElement,
    char = String.fromCharCode(e.keyCode || e.which);
    e.returnValue = false;
    e.cancelBubble = true;
    if (e.preventDefault)
    {
        e.preventDefault();
        e.stopPropagation();
    }//TO HERE, a lot of X-browser issues are adressed
    if (char == +(char) && el.value.length < 10)
    {//format input:
        el.value = (el.value + char).replace(/^([0-9]{0,2})\/*([0-9]{0,2})\/*([0-9]{0,4})$/,function(all, m, d, y)
         {
             m += m.length === 2 ? '/' : '';
             d += d.length === 2 ? '/' : '';
             return m+d+y;
         });
    }
    return e;//done
};
var dateIn = document.getElementById('dateInputElement');
if (dateIn.addEventListener)
{//add event handlers
    dateIn.addEventListener('keypress',keypress, false);
}
else
{
    return dateIn.attachEvent('onkeypress',keypress);
}

To get a better understanding of this code, you might want to take a look here and here.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • How the hell am I supposed to type anything in that input, if every keypress is prevented? Never ever restrict typing, but validate before submission (and maybe live, but unobtrusive) – Bergi May 03 '13 at 14:28
  • @Bergi: It's not the most user-friendly approach, but you _can_ type in that input field, by all means. Though every non-numeric char will be ignored. – Elias Van Ootegem May 03 '13 at 14:29
  • Uh, but you have to start with `0` or `1` for not getting an alert in your face :-) At least it's bad practise to set up an input which does not as an input but detects keystrokes and appends them manually to its value. You cannot correct anything, and it doesn't respect mouse events (copy, paste, move selection). I'd call it user-*unfriendly*… – Bergi May 03 '13 at 14:39
  • @Bergi: I know, it's not the most user friendly approach at all. I wouldn't disallow the arrows, delete and backspace keys, nor would I `alert` all the time, but simply add a leading `0` when required, but that's the OP's job (if he decides to go down this route). I'm just offering up a possible route... – Elias Van Ootegem May 03 '13 at 14:42
  • OK I got it with this: var e = new Date(sdate); var dd = e.getDate(); var mm = e.getMonth()+1; var yyyy = e.getFullYear(); var d= confirm("The date you selected:" +mm+"/"+dd+"/"+yyyy+" is in the future, OK to continue?"); how can I put the mm/dd/yyyy in the if statement to compare? – Lynx May 03 '13 at 14:50
  • @user2267668: just turn both variables into date objects (`new Date()`, the one from the input can be parsed like I did in the fiddle, the other is a known formatted string, which you can parse in a similar fashion) and then compare them: `if (aDateObject > anotherDateObject)`, JS will take care of things for you... – Elias Van Ootegem May 03 '13 at 14:54
  • OK I have it working now with the way I did it (I just created a var for the mm/dd/yyyy) but now lets say someone enters 12/321/2013 it will produce NaN/NaN/NaN...anything on that? – Lynx May 03 '13 at 15:21
  • @user2267668: Check my fiddle: you can't enter 12/321/2013... also check how and where I parse the date string that I got from user input... – Elias Van Ootegem May 03 '13 at 15:37
  • 1
    @EliasVanOotegem: You can, just paste it by dragging with the mouse :-) – Bergi May 04 '13 at 09:23
  • @Bergi: Good point... to avoid issues with that, you'd either have to use a `change` handler (change event is a nightmare in IE, though) or add a listener for mouse events. Perhaps use (part of) validation/formatting code of this in a `submit` handler... – Elias Van Ootegem May 04 '13 at 13:08
1

You can use a library like Date.js to parse user entered strings and other date-like values into a known format. Then compare directly.

if (Date.parse(sdate) > Date.parse(curdate)) {
  ...
}
Dihedral
  • 343
  • 1
  • 12
  • 1
    Until the Date.js team can [get](https://groups.google.com/d/msg/datejs/U7W2DtwzMA8/jAx6IvwQZ2oJ) [their](https://groups.google.com/d/msg/datejs/vTRd7yDX5Lg/lt5ajP9l3VgJ) [act](https://code.google.com/p/datejs/issues) [together](https://code.google.com/p/datejs/source/list) and produce a stable release, I wouldn't recommend using it. Try [moment.js](http://momentjs.com/) instead. – Matt Johnson-Pint May 03 '13 at 14:49
  • @Matt Cool! I had not heard of moment.js. OP, I would also recommend going with that since it seems to be in active development and Date.js hasn't seen activity since 2007? – Dihedral May 03 '13 at 14:57
  • Date.js had some code activity in 2008, and some doc updates in 2009 and 2010, but has 125 open issues and is still in "Alpha-1" release from 2007. – Matt Johnson-Pint May 03 '13 at 14:59
1

Using moment.js, you can do things like:

if (moment(sdate, 'MM/DD/YYYY') > moment(curdate))
...

If you are saying that curdate is representing "now", then just do:

if (moment(sdate, 'MM/DD/YYYY') > moment())
...

If you want to ensure that the date is in a particular format, you can use their validation functions:

if (moment(sdate, 'MM/DD/YYYY').isValid())
...
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Sorry, I commented too soon and overlooked the `.isValid` bit (well, I ignored it). That is addressing the OP's issue with formatting... comment is gone now :P – Elias Van Ootegem May 03 '13 at 14:58