0

Is there a way in Jquery to make the date as standard format (mm/dd/yyyy) no matter how the date is being specified in the text box?

If the user enters 1/1/12 or 01/1/12 or 01/01/12 it should become 01/01/2012. Is there any plugin available to do this since on blur we got to make sure that it is a valid date too (13/12/12 or 1/32/12 or 2/29/2011(leap yr)).

gdoron
  • 147,333
  • 58
  • 291
  • 367
Raja
  • 3,608
  • 3
  • 28
  • 39
  • possible duplicate of [Javascript: how to validate dates in format MM-DD-YYYY?](http://stackoverflow.com/questions/276479/javascript-how-to-validate-dates-in-format-mm-dd-yyyy) – Rafay Feb 15 '12 at 18:16
  • I suggest usig jQueryu UI's Caledar widget. It provides a clea iterface for users to isert a date without maually typig it i. – Only Bolivian Here Feb 15 '12 at 18:17
  • I am not trying to validate the date. I am trying to make the format as standard. ex. If the user enters 1/1/12 then it should become 01/01/2012 on blur. – Raja Feb 15 '12 at 18:20
  • from your question "`since on blur we got to make sure that it is a valid date too`" sounds like validation – Rafay Feb 15 '12 at 18:22
  • @SergioTapia: We are already using Jqyery UI date picker. The prob is the user is so used to typing the dates (historical ones too) and finds it difficult to choose an appropriate date through datepicker. – Raja Feb 15 '12 at 18:22
  • @3nigma: You are right. We want to make it in that format and also validate it. I apologize for the confusion. – Raja Feb 15 '12 at 18:25

3 Answers3

1

I've used date.js before. It's pretty handy. This is not an input control, but it allows you to validate and reformat dates easily.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

I use the maskedinput plugin from here: http://digitalbush.com/projects/masked-input-plugin/

seems to work pretty nice! Works with a datepicker field also.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
0

Here's an example function:

function validateDate() {
    var nums = $(this).val().match(/\d+/g);
    var m = Number(nums[0]) - 1; //month starts from 0
    var d = Number(nums[1]);
    var y = (Number(nums[2]) < 100 ? 2000 : 0) + Number(nums[2]);
    var date = new Date(y,m,d);
    // this is where the date gets validated
    m = (date.getMonth() < 9 ? '0' : '') + (date.getMonth()+1).toString();
    d = (date.getDate() < 10 ? '0' : '') + date.getDate().toString();
    y = date.getFullYear().toString();
    $(this).val(m+'/'+d+'/'+y);
}

$('#date').blur(validateDate);
inhan
  • 7,394
  • 2
  • 24
  • 35
  • You might wanna make sure there are 3 number blocks first, otherwise assign it a default date. That's when user inputs `2/1999` for example. – inhan Feb 15 '12 at 20:11