user3429789 - 1 year ago 123
Javascript Question

# Regular Expression to validate ID number

An ID number consists of 12 digits in the following format: xxxmmddxxxxx - where x is any number (0-9), DD is day (01 to 31) and MM is month (01 to 12). Is there a way to validate that format? I understand that I could check the validity by a simple if statement like

`dd > 0 && dd <=31`
but I'm trying to use regex for the sake of understanding. Appreciate the help.

Try this regex:

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

``````\$("#test").on("keyup", function() {
if (\$(this).val().length == 12) {
var result = \$(this).val().match(/^\d{3}(((0[1-9])|(1[0-2]))((0[1-2])|([1-2][0-9])|(3[0-1])))\d{5}\$/);

\$("#result").text(result ? "valid" : "invalid");
}
});``````
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" maxlength="12" />
<div id="result"></div>``````

Explanation:

``````^                        - start of the string
\d{3}                    - first three digits
(                        - date block
(                    - month block
(0[1-9])         - months from 01 to 09
|                - or
(1[0-2])         - months from 10 to 12
)
(                    - day block
(0[1-9])         - days from 01 to 09
|                - or
([1-2][0-9])     - days from 10 to 29
|                - or
(3[0-1])         - days from 30 to 31
)
)
\d{5}                    - last five digits
\$                        - end of string
``````

I'm not sure if this is the best way to do that. Maybe a regex specialist can show a better one.

Update: Fixed Month=00 and Day=00 issue as @Toto pointed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download