Validation and formatting Date using javascript

Hi,

I want to validate and format date field (mm/dd/yy) using javascript and am looking for sample code snippet.

Valid year=1938 to 1950

Valid i/p o/p (Validation & Formatting)

12345–> 01/23/45
1232009–> 01/23/09
10122014–> 10/12/14
101214—> 10/12/14
10/20/2014–> 10/20/14
10/20/14–> 10/20/14
10-20-14–> 10/20/14
10-20-2014–> 10/20/14

Invalid Dates

12/89/2014->Invalid Date format,since we can’t have date 89
13/12/2014->Invalid Date format,since we can’t have month 13
1234567890->Invalid date format

Thanks in Advance

Also invalid year since you can’t have years past 1950?

There was a typo in the above question,Valid year is from 1938 to 2050

Your best option is to not allow the user to just input anything and then try to format correctly before/during submit. Give a required format, force the user to use that format, whatever your system/app requires.

Modern browsers support the placeholder attribute of input fields. If you want to make it work for older browsers, use javascript onfocus and onblur. Pre-populate the field with “mm/dd/yy”, use onfocus=“if(this.value === ‘mm/dd/yy’){this.value = ‘’}” and onblur=“if(this.value === ‘’){this.value = ‘mm/dd/yy’}” and perform validation to make sure that something like “12/31/14” is entered.

V/r,

:slight_smile:

My guess is he’s working on cleaning up existing unvalidated data.

Hi. To format a date in JavaScript you can use either moment.js:

moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2020-03-20 14:32:20
moment("20161031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20170620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours

Or date format like this:

today = new Date();
today.format('dd-m-yy'); // Returns '02-8-16'

There are other ways as well.