Reputation: 103
I'm trying to create a regex that verifies first 6 numbers of 11 are in this date format 'yymmdd' and verifies it only contains 11 numbers.
Example: 06060612345
^((0[1-9]|[1-2][0-9]|31(?!(?:0[2469]|11))|30(?!02))(0[1-9]|1[0-2])(0?[0-9]|[1-9][0-9]))
Upvotes: 0
Views: 264
Reputation: 883
As stated in the comments using regex for validation doesn't realy work. Make it easier on yourself, by using a regex like const match = "06060612345".match(/^(\d{2})(\d{2})(\d{2})(\d{5})$/)
. Then using Date.parse
:
// Generates our yyyy/mm/dd date string for our argument.
const date = [20 + match[1], match[2], match[3]].join('/');
// And to check validity you can use this instead of the
// massive moment js lib as suggested in the comments.
const isValid = !isNaN(Date.parse(date));
And if needed the extra numbers are in match[4]
.
Upvotes: 1
Reputation: 236
This:
^((0[1-9])|([1-9]{2}))((0[1-9]|1[0-2]))(0[1-9]|[1-2][0-9]|(?<!(?:(0[2469])|11))31|(?<!02)30)\d{5}$
is close to what you're looking for. The format should be fine but it also accepts some invalid dates like 192901
This is also the reason why you want to avoid using regex for such tasks. If you're using it for anything remotely complex. Assuming your regex supports recursion you could use some modulo tricks to check for leap years, but again I really really would advise you against it unless there is a specific reason or it serves a recreational purpose (e.g. some kind of programming challenge)
Upvotes: 1