Regular expression for date format- dd-mm-yyyy in Javascript - javascript

I need a regular expression for date format: dd-mm-yyyy in Javascript.

function parseDate(str) {
var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}

Notice
Your regexp does not work for years that "are multiples of 4 and 100, but not of 400". Years that pass that test are not leap years. For example: 1900, 2100, 2200, 2300, 2500, etc. In other words, it puts all years with the format \d\d00 in the same class of leap years, which is incorrect. – MuchToLearn
So it works properly only for [1901 - 2099] (Whew) 😊
dd-MM-yyyy
Checks if leap year.
Years from 1900 to 9999 are valid. Only dd-MM-yyyy
var stringToValidate = "29-02-2012";
var rgexp = /(^(((0[1-9]|1[0-9]|2[0-8])[-](0[1-9]|1[012]))|((29|30|31)[-](0[13578]|1[02]))|((29|30)[-](0[4,6,9]|11)))[-](19|[2-9][0-9])\d\d$)|(^29[-]02[-](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)/;
var isValidDate = rgexp.test(stringToValidate);

Here is Regex for multiple date formats working for me :
//dd.MM.yyyy
var date_regex = /^(0[1-9]|1\d|2\d|3[01])\.(0[1-9]|1[0-2])\.(19|20)\d{2}$/;
alert(date_regex.test("02.02.1991"));
// //dd/mm/yyyy
// var date_regex = /^(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[0-2])\/(19|20)\d{2}$/;
// alert(date_regex.test("02/12/1991"));
// //dd-mm-yyyy
// var date_regex = /^(0[1-9]|1\d|2\d|3[01])\-(0[1-9]|1[0-2])\-(19|20)\d{2}$/;
// alert(date_regex.test("02-12-1991"));
// //mm/dd/yyyy
// var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
// alert(date_regex.test("12/02/1991"));
// //yyyy.MM.dd
// var date_regex = /^((19|20)\d{2})\.(0[1-9]|1[0-2])\.(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991.12.02"));
// //yyyy/MM/dd
// var date_regex = /^((19|20)\d{2})\/(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991/12/02"));
// //yyyy-MM-dd
// var date_regex = /^((19|20)\d{2})\-(0[1-9]|1[0-2])\-(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991-12-02"));

Try this:
'01-01-2012'.match( /\d{2}-\d{2}-\d{4}/ )
Note that that this way the date 33-12-2022 would be considered valid as well!

'01-01-2012'.match( /(?!3[2-9]|00|02-3[01]|04-31|06-31|09-31|11-31)[0-3][0-9]-(?!1[3-9]|00)[01][0-9]-(?!10|28|29)[12][089][0-9][0-9]/ )
This looks for only valid dates from 1800 to 2099. No leap year support (as in it assumes every year is a possible leap year).

Well, I made this:
'31-12-1987'.match(/(3[01]|[2][0-9]|0\d)-(1[0-2]|0\[1-9])-\d{4}/)
Validates the day from 01 to 31, month from 01 to 12 and year of four digits. It only fails the february 30, and the months without 31 days. Which you can clean using the new Date('mm/dd/yyyy').

This regex is for MM/DD/YYYY and M/D/YYYY
var date_regex = /^(0?[1-9]|1[012])[\/](0?[1-9]|[12][0-9]|3[01])[\/]\d{4}$/;

Working a few of the above together (primarily #gdZeus's) now you can do MM/dd/yyyy | MM-dd-yyyy | MM.dd.yyyy
/(^(((0[1-9]|1[012])[-/.](0[1-9]|1[0-9]|2[0-8]))|((0[13578]|1[02])[-/.](29|30|31))|((0[4,6,9]|11)[-/.](29|30)))[-/.](19|[2-9][0-9])\d\d$)|(^02[-/.]29[-/.](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)/
Additionally if you are using this inline in a js file you can use the following which returns a regexp literal. This will allow you to validate that a date is in the past! This is handy for birthdays. You can reverse it to check that a date is in the future as well (ex. checking credit card exp). This will work almost anywhere in javascript but not if you really need a regexp literal. For example if you are serializing it to a some other format without the ability to run js.
new RegExp('(^(((0[1-9]|1[012])[-/.](0[1-9]|1[0-9]|2[0-8]))|((0[13578]|1[02])[-/.](29|30|31))|((0[4,6,9]|11)[-/.](29|30)))[-/.]('+range(1920, new Date().getFullYear()).join('|')+')$)|(^02[-/.]29[-/.]('+range(1920, new Date().getFullYear()).filter(function(year){if (year % 4 == 0) { return true }}).join('|')+')$)/', 'g')
returns:
/(^(((0[1-9]|1[012])[-\/.](0[1-9]|1[0-9]|2[0-8]))|((0[13578]|1[02])[-\/.](29|30|31))|((0[4,6,9]|11)[-\/.](29|30)))[-\/.](1920|1921|1922|1923|1924|1925|1926|1927|1928|1929|1930|1931|1932|1933|1934|1935|1936|1937|1938|1939|1940|1941|1942|1943|1944|1945|1946|1947|1948|1949|1950|1951|1952|1953|1954|1955|1956|1957|1958|1959|1960|1961|1962|1963|1964|1965|1966|1967|1968|1969|1970|1971|1972|1973|1974|1975|1976|1977|1978|1979|1980|1981|1982|1983|1984|1985|1986|1987|1988|1989|1990|1991|1992|1993|1994|1995|1996|1997|1998|1999|2000|2001|2002|2003|2004|2005|2006|2007|2008|2009|2010|2011|2012|2013|2014|2015)$)|(^02[-\/.]29[-\/.](1920|1924|1928|1932|1936|1940|1944|1948|1952|1956|1960|1964|1968|1972|1976|1980|1984|1988|1992|1996|2000|2004|2008|2012)$)\//g
NOTE: this utilizes underscore's range function to generate the dates. You can write your own though like this very inelegant version :)
function range(start, end) {
var foo = [];
for (var i = start; i <= end; i++) {
foo.push(i);
}
return foo;
}

$('#DOB').blur(function () {
var s = $('#DOB').val(); alert('Entered date is:' + s);
var parms = s.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2], 10);
var d = new Date();
var n = d.getFullYear(); //alert('current year is :' + n);
if (yyyy > n || yyyy < 1900) {
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid year)');
}
var mm = parseInt(parms[1], 10);
if (mm > 12 || mm < 0)
{
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid month');
}
var dd = parseInt(parms[0], 10);
if (dd > 31 || dd < 0)
{
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid day');
}
//var date = new Date(dd, mm - 1, yyyy, 12, 0, 0, 0);
//var ndate = (date.getMonth() + 1) && ddmm === date.getDate() && yyyy === date.getFullYear();
// alert('new date is:' + ndate);
});

This works for me
new RegExp('^(0[1-9]|[1-9]|[12][0-9]|3[01])-(0[1-9]|[1-9]|1[012])-(19|20)\\d\\d$')

/^(\d{1,2})(\/)(\d{1,2})\2(\d{4})\$/

Related

Date validation and relative delta between two dates in javascript

I have an interface where I receive a date in this format: Month/Year, ex: 11/2022.
I would like to verify that this is a valid date.
I use the datatables editor. The configuration (see below) of the field works well, but since the user can enter the date himself without going through the calendar, there is a risk that the date entered is incorrect. It doesn't work like an input mask. So i need to validate the date in the code.
{
type: "datetime",
label: "Date:",
name: "Date",
def: function () { return new Date(); },
format: 'MM/YYYY',
fieldInfo: 'Format: Month/Year (ex: 12/2022)',
keyInput: true
}
The date should not be accepted if the difference between this date and today's date is less than 3 months.
It means that, compared to today, all dates before July will have to be rejected.
Currently I can do this with the relativedelta method of the python dateutil module. But as the validation must be done on the client side, I would like to do this in javascript (which I know very little).
The example below shows how to do this. You should take advantage of the HTML 5 input types to validate your dates. You also need to calculate 3 months from now in myEpoch and then compare it to the date/time given
HTML:
<p>
Date & Time: <input id="foo" type="datetime-local" />
</p>
JavaScript:
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
var foo = document.getElementById("foo");
if (foo.value < myEpoch) {
//show a message saying this date is invalid
}
Since user is entering date in MM/yyyy format, so i'm assuming that you take 1 as a date into account, i.e., if input is 03/2020, you would consider it as: 01/03/2020. Right? If
so, then you can do the following to validate this date:-
function isValidDate(inputDate) {
// Unfortunately JS doesn't have any in-built function to validate date in MM/yyyy format. Hence regex comes to the rescue
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
throw new Error('Unable to parse date.');
}
// Check if it is less than 3 months or not.
var isValid = !isLessThan3Months(new Date(finalDate), new Date());
return isValid;
}
function isLessThan3Months(dateToCompare, currentDate) {
var diffYears = currentDate.getFullYear() - dateToCompare.getFullYear();
var diffMonths = currentDate.getMonth() - dateToCompare.getMonth();
var diffDays = currentDate.getDate() - dateToCompare.getDate();
var months = diffYears * 12 + diffMonths;
if (diffDays > 0) {
months += '.' + diffDays;
} else if (diffDays < 0) {
months--;
months +=
'.' +
(new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate() + diffDays);
}
return months < 3;
}
isValidDate('03/2020');
So now, by calling isValidDate with user's input date in MM/yyyy format, you should be able to check if it is valid or not.
For this, you won't need to use any third party javascript library. Just plain javascript is enough.
You should probably use Moment.js, because working with the raw Date object is fiddly.
If you would rather use plain JavaScript, then the following might be of use:
const moreThan3MonthsHence = ({ utcYear, utcMonth },
now = new Date,
target = new Date(Date.UTC(utcYear, utcMonth)),
threeMonthsHence = addMonths(new Date(now.valueOf()), 3)) =>
(target > threeMonthsHence)
const validate = (str,
[utcMonth, utcYear] = str.split('/'),
date = new Date(Date.UTC(+utcYear, (+utcMonth)-1))) =>
moreThan3MonthsHence({ utcYear: date.getUTCFullYear(), utcMonth: date.getUTCMonth() })
const addMonths = (date, months, d = date.getDate()) => {
date.setMonth(date.getMonth() + +months);
// If rolled over to next month, set to last day of previous month
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Note: input is one-based months
console.log(validate('07/2020')) // true
console.log(validate('06/2020')) // false
console.log(validate('12/2019')) // false
Notes
now is internally represented as the milliseconds since the Unix epoch. Note this includes the current time of day.
target is the milliseconds since the Unix epoch of midnight on the supplied UTC date.
threeMonthsHence is the milliseconds since the Unix epoch of now (including time of day), plus three months.
validate parses the input string.
addMonths is necessary because the built-in function can roll-over into a new month with unexpected behavior.
Finally to solve my problem I mixed the solutions proposed by #Sumit Parakh and #ControlAltDel.
function isValidDate(inputDate) {
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
var parsedDate = 0;
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
else {
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
parsedDate = 0;
//throw new Error('Unable to parse date.');
}
return parsedDate;
}
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
finalDate = isValidDate(date_peremption.val());
if (finalDate == 0){
date_received.error("This date is invalid");
}
else if(finalDate < myEpoch) {
date_received.error("The date must be more than three months last");
}
It's not very elegant, but it works. Thanks everyone

How to format javascript date object?

i have 2 date fields which i want to compare their values. The problem is that i need the dates to be in dd/mm/yyyy format and as js date object. How can i change the date object format to receive dd/mm/yyyy and compare them with this format?
Here is what i've tried so far...
$('#date_customFrom').datepicker({
format: "dd/mm/yyyy"
});
$('#date_customTo').datepicker({
format: "dd/mm/yyyy"
});
$('.submit').on('click', function() {
var start_date = $("input[name='date_customFrom']").val().split("/");
var end_date = $("input[name='date_customTo']").val().split("/");
var new_date_start = new Date(start_date[2], start_date[1] - 1,
start_date[0]);
var new_date_end = new Date(end_date[2], end_date[1] - 1, end_date[0]);
console.log(new_date_start);
console.log(new_date_end);
});
fiddle
var dd = new_date_start.getDate();
var mm = new_date_start.getMonth() + 1;//January is 0!
var yyyy = new_date_start.getFullYear();
if (dd < 10) { dd = '0' + dd }
if (mm < 10) { mm = '0' + mm }
var res_START= dd + '/' + mm + '/' + yyyy;
console.log(res_START);
TRY THIS
You need use Moment.js
Here is doc
var momDt = moment('10.12.2016', 'DD/MM/YYYY');
You can compare Date objects with basic relational operators.
Make sure you are converting to numbers after splitting the string, using + or parseInt;
+(start_date[2])
Number(start_date[2])
parseInt(start_date[2], 10)
or map Number constructor after splitting
var start_date = $("input[name='date_customFrom']").val().split("/").map(Number);
new Date(start_date[2], start_date[1] - 1, start_date[0]);
Use <, <=, >, >= to compare now.
var start, end;
start = new Date(2016, 11, 5);
end = new Date(2016, 11, 4);
console.log(start, end, start < end)
start = new Date(2016, 11, 3);
end = new Date(2016, 11, 4);
console.log(start, end, start < end)
Fist of all, you do not need to cast the dates... the datepicker already can give you dates:
var start_date = $("#date_customFrom").datepicker('getDate');
var end_date = $("#date_customTo").datepicker('getDate');
Second, the correct format of the date is the date picker is
$('#date_customFrom').datepicker({
dateFormat: "dd/mm/yyyy"
});
Check this for the entire list of formats
http://api.jqueryui.com/datepicker/#utility-formatDate
Third, comparison is simply using relational comparison
if (start_date > end_date) {
}
You can create a format function:
function formatDate(date, search, replacement)
{
var target = date.toISOString().slice(0, 10);
return target.split(search).join(replacement);
}
and use it:
formatDate(new_date_start, "-", "/")
Here is your updated fiddle
But I agree with asdf_enel_hak's comment that moment.js would be a much better solution for you.
Update
I've just realized that the above will not take into consideration your timezone, so here is an updated function:
function formatDate(date, search, replacement)
{
var target = new Date(date);
target.setMinutes(date.getMinutes() - date.getTimezoneOffset());
target = target.toJSON().slice(0, 10);
return target.split(search).join(replacement);
}
And new fiddle

How to test the Date, Month and Year entered as 2 Digits are valid?

In my form, a user can enter the date like this: 220875 (day, month, year).
Once they entered the details, I would like to test that the date is valid:
Month is from 1 to 12 inclusive.
The day entered is valid for the specified month.
How would I find out whether or not the values are correct and matching?
here is my attempt: (excerpt)
DateIsOk:function(value) { //220875 for example
var formatValue = value.match(/.{1,2}/g), //splting as 22 08 75
fieldDate = parseInt(formatValue[0]), //converting to num
fieldMonth = parseInt(formatValue[1]),
fieldYear = parseInt(formatValue[2]),
dayobj = new Date();
//test need to go here...
}
If it helps, here is a Live Demo.
It seems you use the DD/MM/YYYY format.
So you can easily use this ready-to-use code: http://www.qodo.co.uk/blog/javascript-checking-if-a-date-is-valid/
JavaScript
// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
If you don't mind using momentjs as #hVostt suggested, you could try modifying your DateIsOk() validation function like this:
...
dateParts : ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"],
DateIsOk:function(value) {
var dayobj = moment(value, "DDMMYY");
if (dayobj.isValid()) {
this.errorHandler(true);
return true;
}
else {
this.errorHandler('Invalid ' + this.dateParts[dayobj.invalidAt()]);
return false;
}
}
...
Here's the updated Live Demo
The js regexp maybe like this
/([0-2][0-9]|3[01])(0[1-9]|1[0-2])(\d{2})/
Please try Moment.js and his validation functions:
http://momentjs.com/docs/#/parsing/is-valid/
moment([2014, 25, 35]).isValid();
moment("2014-25-35").isValid();

javascript date validation not validation February 31

I am trying to write some code with will validate form data. I have a date field which should have a mm/dd/yyyy format. I needed to catch exceptions such as February 31, so I added this code:
var d = new Date(dob);
if (isNaN(d.getTime())) { //this if is to take care of February 31, BUT IT DOESN'T!
error = 1;
message += "<li>Invalid Date</li>";
} else {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var validFormat = date_regex.test(dob);
if (!(validFormat)) {
error = 1;
message += "<li>Invalid date format - date must have format mm/dd/yyyy</li>";
}
}
However I found something very weird: while the date 02/32/2000 errors as an invalid date, 02/31/2000 does not!
Due to what I said in the comments...
Another way you could check if a date is valid is by checking whether or not the stuff you passed into the new Date function is the same as what comes out of it, like this:
// Remember that the month is 0-based so February is actually 1...
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
then you could do this:
if (isValidDate(2013,1,31))
and it would return true if valid and false if invalid.
After wrecking my head with the obscurity of Date .getMonth() (and also weekday by .getDay()) being 0-index (despite year, day and all the others not being like so... oh god...) I've re-wrote Jeff's answer to make it more readable and more friendly-usable to whom consume the method from outside.
ES6 code
You can call passing month as 1-indexed as you'd normally expect.
I've parsed inputs using Number constructor so I can use strict equality to more confidently compare values.
I'm using the UTC version methods to avoid having to deal with the local timezone.
Also, I broke steps down into some variables for the sake of readability.
/**
*
* #param { number | string } day
* #param { number | string } month
* #param { number| string } year
* #returns { boolean }
*/
function validateDateString(day, month, year) {
day = Number(day);
month = Number(month) - 1; //bloody 0-indexed month
year = Number(year);
let d = new Date(year, month, day);
let yearMatches = d.getUTCFullYear() === year;
let monthMatches = d.getUTCMonth() === month;
let dayMatches = d.getUTCDate() === day;
return yearMatches && monthMatches && dayMatches;
}
Are you able to use a library?
My first port of call for date handling in Javascript is moment.js: "A javascript date library for parsing, validating, manipulating, and formatting dates."
The ususal way to validate a 'mm/dd/yyyy' date string is to create a date object and verify that its month and date are the same as the input.
function isvalid_mdy(s){
var day, A= s.match(/[1-9][\d]*/g);
try{
A[0]-= 1;
day= new Date(+A[2], A[0], +A[1]);
if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
isvalid_mdy('02/31/2000')
/* returned value: (Error)Bad Date */
Assuming month input is 1-12 (1-based, not 0-based):
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day);
return month == d.getMonth() + 1;
}
isValidDate(2019, 12, 0); //=> false
isValidDate(2020, 2, 29); //=> true
isValidDate(2021, 2, 29); //=> false
isValidDate(2022, 2, 31); //=> false
Basically an alternative to the above-mentioned examples
function (date) {
if (!/(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([1-2][0-9]{3})/g.test(date))
{
alert('Incorrect date format please follow this form: dd/mm/yyyy');
return;
}
else
{
// secondary validation
const parts = (date).split('/').map((p) => parseInt(p, 10));
let day = Number(parts[0]);
let month = Number(parts[1]) - 1; // 0-indexed month
let year = Number(parts[2]);
let d = new Date(year, month, day);
if (!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day))
{
alert('Incorrect date, please enter the correct day entry');
return;
}
}
}
I may be a little late for posting an answer but here is what worked best for me
var user_date = (`${user_values.month_value} ${user_values.date_value} , ${user_values.year_value}`)
const d = new Date(user_date);
let day = d.getDate()
if(user_values.date_value != day){
setdate_validation({
display:'flex'
})
}
else{
setdate_validation({
display:'none'
})
console.log(user_values)
so in the above code what happens is i get different inputs from my user like one dropdown for date another for month and so on , i collect them and store it with .getdate() now .getdate() function returns the value of day , so if i stored (02 21 , 2002) then the .getdate() will return 21 ,
but there is a catch if i enter an invalid date like (02 30, 2002) where 30 is invalid in month of february then the .getdate() function returns not the same date but the date in next month or increment as much you are far away from a valid date like if 28 is valid and I entered 29 then .getdate() will show 1 as the output so i just compare the result of .getdate() with my current date value which is entered and if it is not same then the date is invalid.
(this code is from react using usestates)

Javascript regex help

Does anybody know how I can make the forwardslash and format: dd/mm/yyyy compulsory in this regex?
// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
for mandatory dd/mm/yyyy try:
var dateFormat = /^\d{2}\/\d{2}\/\d{4}$/;
I didn't look to closely at the rest of the function, but I think that is what you were going for.
this would do it i think..
/^\d{2}\/\d{2}\/\d{4}$/
forced 2 digit days, 2 digit months, 4 digit years and / as seperator..
or
/^[0-3][0-9]\/[0-1][0-9]\/\d{4}$/
to enforce a little bounds control..
day: 00-39
month: 00-19

Categories

Resources