Penguen
Penguen

Reputation: 17278

Check dateformat with regex in JS

My question is simple but takes work. I tried lots of regex expressions to check my datetime is ok or not, but though I am sure my regex exprerssion is correct it always return to me isnotok with ALERT. Can you check my code?


validateForLongDateTime('22-03-1981')



function validateForLongDateTime(date){
    var regex=new RegExp("/^\d{2}[.-/]\d{2}[.-/]\d{4}$/");
    var dateOk=regex.test(date);
    if(dateOk){
      alert('ok');

    }else{
        alert('notok');
    }
}


Upvotes: 1

Views: 86

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

There are at least 2 issues with the regex:

  • It has unescaped forward slashes
  • The hyphen in the character classes is unescaped and forms a range (matching only . and /) that is not what is necessary here.

enter image description here

The "fixed" regex will look like:

/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/

See demo

However, you cannot validate dates with it since it will also match 37-67-5734.

Here is my enahanced version with a character class for the delimiter:

^(?:(?:31([\/.-])(?:0?[13578]|1[02]))\1|(?:(?:29|30)([\/.-])(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29([\/.-])0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])([\/.-])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

Upvotes: 2

Yes Kay Selva
Yes Kay Selva

Reputation: 584

this way you can validate date between 1 to 31 and month 1 to 12

var regex = /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d$/

see this demo here https://regex101.com/r/xP1bD2/1

Upvotes: 0

Related Questions