Looking for a regex to validate Cuban identity car

2019-09-22 04:18发布

问题:

I need an example of how to validate an identification number in the Cuban identification card format. I'm looking for the regex validation in html5.

The format description:

Date of Birth (yymmdd) and 5 digits
There are 11 total digits.

Example: 89103024100

回答1:

Note: this is uses rough date validation via pure RegEx (ie. any month can have up to 31 days):

[0-9]{2}(?:0[0-9]|1[0-2])(?:0[1-9]|[12][0-9]|3[01])[0-9]{5}

You can test if a string matches via JavaScript like so:

/[0-9]{2}(?:0[0-9]|1[0-2])(?:0[1-9]|[12][0-9]|3[01])[0-9]{5}/.test('82061512345');
// returns true because it is valid

If you need true date validation I would do something like the following:

var id1 = '82061512345'; // example valid id
var id2 = '82063212345'; // example invalid id

function is_valid_date(string) {
    var y = id.substr(0,2); // 82 (year)
    var m = id.substr(2,2); // 06 (month)
    var d = id.substr(4,2); // 15/32 (day)
    if (isNaN(Date.parse(y + '-' + m + '-' + d)) {
        return false;
    } else {
        return true;
    }
}

is_valid_date(id1); // returns true
is_valid_date(id2); // returns false

And you can tack on the following for full id validation:

function is_valid_id(id) {
    if (/[0-9]{11}/.test(id) && is_valid_date(id)) {
        return true;
    } else {
        return false;
    }
}

is_valid_id(id1); // returns true
is_valid_id(id2); // returns false


回答2:

/(\d{2}((0[1-9]|1[012])(0[1-9]|1\d|2[0-8])|(0[13456789]|1[012])
(29|30)|(0[13578]|1[02])31)|([02468][048]|[13579][26])0229)[0-9]{5}/.test('00023012345');

return false //is not a leap year

/(\d{2}((0[1-9]|1[012])(0[1-9]|1\d|2[0-8])|(0[13456789]|1[012])
(29|30)|(0[13578]|1[02])31)|([02468][048]|[13579][26])0229)[0-9]{5}/.test('00022912345');

return true //a leap year