I have to check if CPR is valid so I have to check these things:
- CPR have 9 digit only
- The first 2 digits represent the birth year from 1980 to 2023 so going to take only the last two digit of year for the first two digit for cpr
- then the (3rd/4th) digits in CPR represent the
month (i.e. 800412233 is born in Year 1980 and in Month 04).
The range of the year and month must be valid and last The last 5 digits is any random digits for 0 to 9.
This is what I did, but all the CPR are shown as invalid
^(([8-9][0-9]|[0-1][0-9]|2[0-3]){2})(0[1-9]|1[0-2])(d{5})$
3
Answers
Use
^([01289])d(0[1-9]|1[012])d{5}$
. See regex demonstratorAt some point you’re going to need to make a change to the validation rules and you’re going to come back to this code and go "WTF does this regex even do?", and that might be as little as a week from now.
Breaking it our into substrings is easy, far more readable, and far more extensible. Eg: How would you add a descriptive error message to the regex code?
Output:
Try