0

I need a regex which takes the string YYYY-MM-DD-XXXX (The last 4 are just for purpose of gender/area) It's mostly important to check the first 8 Digits for a valid birth date.

So far i have this:

/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})\-([0-9]{4})$/

Also i want to check so the input age is at least 18 years old. Would appreciate if somone had some input on how to achieve this.

Edit: The regex above was tested in JS, but should work fine in ASP as well?

ekad
  • 14,436
  • 26
  • 44
  • 46
rac
  • 263
  • 2
  • 7
  • 13

3 Answers3

0

I have changed your regex a bit to make it look more authentic

^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$

years like 3012 will not pass.

Now you want to find whether a person is 18 years or not.

One approach could be to find the difference between the years of dates provided like this

var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var year_now = new Date().getFullYear();
console.log(year_now-res[1]);

a second approach will be more precise one :

var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1],res[2],res[3]);
console.log(todays_date-birth_date);

will output the result in milliseconds. You can do the math to convert it into year

Cheers , Hope that helps !

aelor
  • 10,892
  • 3
  • 32
  • 48
0

I suggest using moment.js which provides an easy to use method for doing this.

interactive demo

function validate(date){
    var eighteenYearsAgo = moment().subtract("years", 18);
    var birthday = moment(date);

    if (!birthday.isValid()) {
        return "invalid date";    
    }
    else if (eighteenYearsAgo.isAfter(birthday)) {
        return "okay, you're good";    
    }
    else {
        return "sorry, no";    
    }
}

To include moment in your page, you can use CDNJS:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

Source

Community
  • 1
  • 1
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
0

The following will match any year with a valid day/month combination, but won't do validation such as checking you've not entered 31 days for February.

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

Not sure exactly what you're trying to achieve but I'd suggest using a date library for this sort of thing. You could return a message to the user somehow if the entered date fails to parse into an object.

In order to do age validation, you will certainly need to use a library so a regex should only be used for date validation purposes

arco444
  • 22,002
  • 12
  • 63
  • 67