2

pls can somebody give the date validation regex, which will allow the following rules are

  1. It should allow mm/dd/yyyy, m/d/yyyy, mm/d/yyyy, m/d/yyyy (not allow yy)
  2. Number of days for month (30 and 31) validation.
  3. Feb month validation for leap & non leap years.
4
  • 1
    [0-9]{1,2}/[0-9]{1,2}/[0-9]{4} or see stackoverflow.com/questions/5465375/… Commented May 9, 2013 at 13:06
  • 2
    @MarioDeSchaepmeester: please do not post LMGTFY links. Commented May 9, 2013 at 13:19
  • 1
    @thg435 It's the first time I've ever done so, don't worry I'm not planning to do this more. This question just asked for it.. Commented May 9, 2013 at 13:24
  • 1
    @MarioDeSchaepmeester Before giving those type of comments, pls think once, who know's how to use Stack Overflow,they don't know how to use google... Commented May 9, 2013 at 19:18

3 Answers 3

3

Don't try to parse date entirely with regex!Follow KISS principle..

1>Get the dates with this regex

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

2> Validate month,year,day if the string matches with above regex!

var match = myRegexp.exec(myString);
parseInt(match[0],10);//month
parseInt(match[1],10);//day
parseInt(match[2],10);//year
Sign up to request clarification or add additional context in comments.

3 Comments

parseInt(match[0], 10) is the correct syntax.
@Mr_Green yes..you are right specially in case if the digits start with 0 but this feature has been deprecated so anyway it would be base 10..
Even Ecmascript 5 recommends radix.
2

Try this:

([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2}) 

and then if you got a valid string from the above regex then with string manipulations, do something like below:

if(/([0-9][1-2])\/([0-2][0-9]|[3][0-1])\/((19|20)[0-9]{2})/.test(text)){
    var tokens = text.split('/');  //  text.split('\/');
    var day    = parseInt(tokens[0], 10);
    var month  = parseInt(tokens[1], 10);
    var year   = parseInt(tokens[2], 10);
}
else{
    //show error
    //Invalid date format
}

Comments

1

Here's a full validation routine

var myInput = s="5/9/2013";
var r = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
if(!r.test(myInput)) {
  alert("Invalid Input");
  return;
}
var a = s.match(r), d = new Date(a[3],a[1] - 1,a[2]);
if(d.getFullYear() != a[3] || d.getMonth() + 1 != a[1] || d.getDate() != a[2]) {
  alert("Invalid Date");
  return;
}

// process valid date

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.