开发者

Javascript date regex DD/MM/YYYY

I know there are a lot of regex threads out there by I need a specific pattern I couldn't fin anywhere

This regex validates in a YYYY-MM-DD format

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

I need the pattern to be DD/MM/YYYY (day first since it's in spanish and only "/", "-" should not be allowed)

I searched several regex libraries and I think this one should work... but since I'm not familiar with regex I'm not sure it validates like that

(0[1-9]|[12开发者_运维百科][0-9]|3[01])[ \.-](0[1-9]|1[012])[ \.-](19|20|)\d\d

I also don't know ho to escape the slashes, I try to "see" the logic in the string but it's like trying "see" the Matrix code for me. I'm placing the regex string in a options .js

[...]  },
"date": {
                    "regex": (0[1-9]|[12][0-9]|3[01])[ \.-](0[1-9]|1[012])[ \.-](19|20|)\d\d,
                    "alertText": "Alert text AAAA-MM-DD"
                },
"other type..."[...]

So, if the regex is ok, how would I escape it? if it's not, what's the correct regex and how do I escape it? :P

Thanks a lot


You could take the regex that validates YYYY/MM/DD and flip it around to get what you need for DD/MM/YYYY:

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

BTW - this regex validates for either DD/MM/YYYY or DD-MM-YYYY

P.S. This will allow dates such as 31/02/4899


A regex is good for matching the general format but I think you should move parsing to the Date class, e.g.:

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;
}

Now you can use this function to check for valid dates; however, if you need to actually validate without rolling (e.g. "31/2/2010" doesn't automatically roll to "3/3/2010") then you've got another problem.

[Edit] If you also want to validate without rolling then you could add a check to compare against the original string to make sure it is the same date:

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

[Edit2] If you want to match against zero-padded dates (e.g. "08/08/2013") then you could do something like this:

function parseDate(str) {
  function pad(x){return (((''+x).length==2) ? '' : '0') + x; }
  var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)
    , d = (m) ? new Date(m[3], m[2]-1, m[1]) : null
    , matchesPadded = (d&&(str==[pad(d.getDate()),pad(d.getMonth()+1),d.getFullYear()].join('/')))
    , matchesNonPadded = (d&&(str==[d.getDate(),d.getMonth()+1,d.getFullYear()].join('/')));
  return (matchesPadded || matchesNonPadded) ? d : null;
}

However, it will still fail for inconsistently padded dates (e.g. "8/08/2013").


Take a look from here https://www.regextester.com/?fam=114662

Use this following Regular Expression Details, This will support leap year also.

var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([1][26]|[2468][048]|[3579][26])00))))$/g;

Example


Scape slashes is simply use \ before / and it will be escaped. (\/=> /).

Otherwise you're regex DD/MM/YYYY could be next:

/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g

Explanation:

  • [0-9]: Just Numbers
  • {2} or {4}: Length 2 or 4. You could do {2,4} as well to length between two numbers (2 and 4 in this case)
  • [\/]: Character /
  • g : Global -- Or m: Multiline (Optional, see your requirements)
  • $: Anchor to end of string. (Optional, see your requirements)
  • ^: Start of string. (Optional, see your requirements)

An example of use:

var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;

var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09", 
    "2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
    "23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];

//Iterate array
dates.forEach(
    function(date){
        console.log(date + " matches with regex?");
      console.log(regex.test(date));
    });

Of course you can use as boolean:

if(regex.test(date)){
     //do something
}


I use this function for dd/mm/yyyy format :

// (new Date()).fromString("3/9/2013") : 3 of september
// (new Date()).fromString("3/9/2013", false) : 9 of march
Date.prototype.fromString = function(str, ddmmyyyy) {
    var m = str.match(/(\d+)(-|\/)(\d+)(?:-|\/)(?:(\d+)\s+(\d+):(\d+)(?::(\d+))?(?:\.(\d+))?)?/);
    if(m[2] == "/"){
        if(ddmmyyyy === false)
            return new Date(+m[4], +m[1] - 1, +m[3], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
        return new Date(+m[4], +m[3] - 1, +m[1], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
    }
    return new Date(+m[1], +m[3] - 1, +m[4], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}


Try using this..

[0-9]{2}[/][0-9]{2}[/][0-9]{4}$

this should work with this pattern DD/DD/DDDD where D is any digit (0-9)


((?=\d{4})\d{4}|(?=[a-zA-Z]{3})[a-zA-Z]{3}|\d{2})((?=\/)\/|\-)((?=[0-9]{2})[0-9]{2}|(?=[0-9]{1,2})[0-9]{1,2}|[a-zA-Z]{3})((?=\/)\/|\-)((?=[0-9]{4})[0-9]{4}|(?=[0-9]{2})[0-9]{2}|[a-zA-Z]{3})

Regex Compile on it

2012/22/Jan
2012/22/12 
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012-Dec-22
2012-12-22
23/12/2012
23/12/2012
Dec-22-2012
12-2-2012
23-12-2012
23-12-2012


If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.

RegEx for date is actually unwieldy and hard to get right especially with leap years and all.


For people who needs to validate years earlier than year 1900, following should do the trick. Actually this is same as the above answer given by [@OammieR][1] BUT with years including 1800 - 1899.

/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((18|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((18|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/

Hope this helps someone who needs to validate years earlier than 1900, such as 01/01/1855, etc.

Thanks @OammieR for the initial idea.


Do the following change to the jquery.validationengine-en.js file and update the dd/mm/yyyy inline validation by including leap year:

"date": {
    // Check if date is valid by leap year
    "func": function (field) {
    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
    var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
    var match = pattern.exec(field.val());
    if (match == null)
    return false;

    //var year = match[1];
    //var month = match[2]*1;
    //var day = match[3]*1;
    var year = match[3];
    var month = match[2]*1;
    var day = match[1]*1;
    var date = new Date(year, month - 1, day); // because months starts from 0.

    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"


I build this regular to check month 30/31 and let february to 29.

new RegExp(/^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/)

I think, it's more simple and more flexible and enough full.

Perhaps first part can be contract but I Don't find properly.


This validates date like dd-mm-yyyy

([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)([0-9][0-9][0-9][0-9])

This can use with javascript like angular reactive forms


It can be done like this for dd/mm/yyyy:

^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])/[0-9]{4}$

For mm/dd/yy, mm/dd/yyyy, dd/mm/yy, and dd/mm/yyyy:

Allowing leading zeros to be omitted:

^[0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}$

Requiring leading zeros:

^[0-3][0-9]/[0-3][0-9]/(?:[0-9][0-9])?[0-9][0-9]$

For more details: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s04.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜