skip to Main Content

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


  1. Use ^([01289])d(0[1-9]|1[012])d{5}$ . See regex demonstrator

    Login or Signup to reply.
  2. At 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?

    function validate($str) {
        $yr = intval(substr($str, 0, 2));
        $mo = intval(substr($str, 2, 2));
        $code = substr($str, 4);
        
        if( !(($yr >= 80 && $yr <= 99) || ( $yr >= 0 && $yr <= 23)) ) {
            echo "Year $yr out of range.n";
            return false;
        }
        if( $mo < 1 || $mo > 12 ) {
            echo "Month $mo out of range.n";
            return false;
        }
        return true;
    }
    
    var_dump(
        validate('800412233'),
        validate('790412233'),
        validate('240412233'),
        validate('800012233'),
        validate('801312233'),
    );
    

    Output:

    Year 79 out of range.
    Year 24 out of range.
    Month 0 out of range.
    Month 13 out of range.
    bool(true)
    bool(false)
    bool(false)
    bool(false)
    bool(false)
    
    Login or Signup to reply.
  3. Try

    ^([0189][0-9]|2[0-3])(0[1-9]|1[1-2])(d{5})$
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search