CNIC Validation with Regex: Checking the Format
Published · 5 min read
A Pakistani CNIC (Computerised National Identity Card) number has 13 digits. On forms, receipts and letters it is usually written in three groups separated by dashes: five digits, seven digits, then a single digit, as in 12345-1234567-1. That predictable shape makes it a natural job for a regular expression. This guide shows how to write a CNIC pattern, how to accept the formats people actually type, how to pull CNIC-shaped numbers out of longer text, and, just as important, where a regex stops being useful.
The basic CNIC pattern
Translating the 5-7-1 layout into regex is direct. \d{5} means exactly five digits, a literal dash follows, then \d{7}, another dash, and a final \d. Wrap it in anchors so the whole input has to match, not just part of it:
^\d{5}-\d{7}-\d$The ^ and $ anchors matter. Without them, 12345-1234567-1 would also be found inside 9912345-1234567-15, and a form would happily accept garbage around a valid-looking core. If anchors are new to you, the anchors lesson covers them, and counted quantifiers explains the {5} and {7} syntax.
Using it in JavaScript
const CNIC = /^\d{5}-\d{7}-\d$/;
function isCnicShape(input) {
return CNIC.test(input.trim());
}
isCnicShape("12345-1234567-1"); // true
isCnicShape("12345-123456-1"); // false (only 6 digits in the middle)
isCnicShape("1234512345671"); // false (no dashes)Using it in Python
import re
CNIC = re.compile(r"[0-9]{5}-[0-9]{7}-[0-9]")
def is_cnic_shape(value: str) -> bool:
return CNIC.fullmatch(value.strip()) is not None
print(is_cnic_shape("12345-1234567-1")) # True
print(is_cnic_shape("12345-1234567")) # FalseTwo details in the Python version are deliberate. fullmatch replaces the anchors, because it only succeeds when the entire string matches. And the pattern uses [0-9] instead of \d. In Python 3, \d on a normal string matches any Unicode decimal digit, including Arabic-Indic and Extended Arabic-Indic digits, which can appear when text is pasted from Urdu-language sources. If your back end expects ASCII digits only, say so explicitly with [0-9] or the re.ASCII flag. In JavaScript, \d is always ASCII-only, even with the u flag.
Accepting real-world input
People do not always type the dashes. Some paste the 13 digits as one block, some add spaces, and some mix the two. You have a few reasonable options, and the right one depends on how strict the form needs to be.
Option 1: dashed or plain, nothing in between
Use alternation inside a non-capturing group to allow exactly two layouts: the dashed form or 13 plain digits.
^(?:\d{5}-\d{7}-\d|\d{13})$This rejects half-formatted input such as 12345-12345671, which has one dash but not the other. That is usually what you want when the value is going straight into a database.
Option 2: normalise first, then validate
The friendlier approach is to strip everything that is not a digit, check that exactly 13 digits remain, and then reformat the number yourself. The user can type it however they like, and you always store one consistent shape.
function normaliseCnic(input) {
const digits = input.replace(/[\s-]/g, "");
if (!/^\d{13}$/.test(digits)) return null;
return digits.replace(/^(\d{5})(\d{7})(\d)$/, "$1-$2-$3");
}
normaliseCnic("12345 1234567 1"); // "12345-1234567-1"
normaliseCnic("1234512345671"); // "12345-1234567-1"
normaliseCnic("12345-12345-1"); // nullThe last line uses capture groups and $1-$2-$3 in the replacement string to rebuild the dashed layout. The replace with groups lesson walks through that technique step by step. Note that the clean-up only removes whitespace and dashes. Letters or other symbols are left in place, so the 13-digit check rejects them instead of silently deleting them.
Finding CNIC numbers inside longer text
Validation asks whether a whole value has the right shape. Extraction asks where CNIC-shaped values appear inside a larger document, such as an exported spreadsheet column or a block of notes. The difference is mainly about anchors, as explained in validation vs extraction. For extraction, replace ^ and $ with word boundaries and add the g flag:
\b\d{5}-\d{7}-\d\bconst text = "Applicant: Ali Test, CNIC 12345-1234567-1. Old ref 1234-1234567-1.";
const found = text.match(/\b\d{5}-\d{7}-\d\b/g) ?? [];
console.log(found); // ["12345-1234567-1"]The \b on each side stops the pattern from starting or ending in the middle of a longer run of digits, so 112345-1234567-1 and 12345-1234567-12 are both ignored. A word boundary does treat a dash as a separator, so a string like 12345-1234567-1-9 would still produce a match. If that matters for your data, swap the boundaries for lookarounds that reject a neighbouring digit or dash: (?<![\d-]) before and (?![\d-]) after.
What a regex cannot tell you
It is worth being precise about the limits, because a format check is easy to over-trust.
- It cannot confirm that a number was issued.
12345-1234567-1passes every pattern in this article and is obviously made up. - It cannot confirm ownership. A correctly shaped number typed by the wrong person still passes.
- It cannot confirm that a card is current. Expiry and status live with the issuing authority, not in the digits.
- It does not interpret individual digits. This article deliberately makes no claims about what particular positions mean; treat the number as an opaque 13-digit identifier.
If you genuinely need to verify identity, that requires an authorised verification service or a manual check of the document, not a pattern. A regex is still valuable as the first gate: it catches typos, missing digits and pasted junk before a request ever reaches slower or more expensive checks.
Privacy: handle ID numbers with care
A national identity number is sensitive personal data. A few habits go a long way:
- Only collect a CNIC when you actually need it, and say why on the form.
- Do not log full ID numbers in analytics, error reports or debugging output. Mask them, for example
12345-*******-1. - Do not paste real ID numbers into online tools that send your text to a server. Use fictional test values like
12345-1234567-1while building and testing patterns. - Limit who can read stored numbers, and delete them when they are no longer needed.
Common mistakes
- Forgetting the anchors.
\d{5}-\d{7}-\dwithout^and$validates any string that merely contains a CNIC-shaped run, including one with extra digits on either side. - Using
\d+or\d*. A loose quantifier accepts any number of digits, so the 5-7-1 structure is lost. Counted quantifiers keep each group exact. - Storing a number as an integer. A CNIC is an identifier, not a quantity. Keep it as text so leading zeros and the dashed format survive.
- Silently deleting characters. Stripping only spaces and dashes before checking is fine; stripping every non-digit can turn a typo into a different, wrongly accepted number.
Testing your pattern
Before shipping any validator, test it against a short list of values that should pass and values that should fail. For CNIC shapes, a useful set looks like this:
- Should pass:
12345-1234567-1, and1234512345671if you accept the plain form. - Should fail:
1234-1234567-1(four digits first),12345-123456-1(six in the middle),12345-1234567-12(two at the end),12345-1234567-A, and an empty string. - Decide explicitly: leading or trailing spaces, spaces instead of dashes, and Unicode digits.
You can paste the pattern and these samples straight into the RegexLab tester to see every match highlighted, or start from the ready-made Pakistan CNIC pattern in the library and adjust it to your rules.
Open the library entry with the CNIC regex, test samples and code in several languages. Pakistan CNIC pattern →
Frequently asked questions
- What is the regex for a Pakistani CNIC number?
- For the dashed format use ^\d{5}-\d{7}-\d$. To also accept 13 plain digits, use ^(?:\d{5}-\d{7}-\d|\d{13})$.
- Can a regex tell me whether a CNIC is real?
- No. A regex only checks that the input has the right shape. It cannot confirm that the number was issued, is current, or belongs to the person entering it.
- Should I store CNIC numbers with or without dashes?
- Either works, as long as you pick one format and normalise every input to it. Stripping spaces and dashes, checking for 13 digits and then reformatting is a reliable approach.
- Is it safe to test CNIC patterns in RegexLab?
- RegexLab processes everything locally in your browser and sends nothing to a server. Even so, use fictional values such as 12345-1234567-1 rather than real ID numbers.
Related posts
- How to Extract Anything from Text with RegexA repeatable regex method for pulling codes, emails, dates and amounts out of messy text, with tested patterns and JavaScript and Python code.
- How to Clean Messy Data with RegexPractical regex find-and-replace recipes for messy data: whitespace, duplicate words and lines, dates, phone numbers, leftover HTML and CSV fields.
- Regex for Beginners: A Practical IntroductionLearn regex from scratch: literals, character sets, quantifiers, anchors, groups and flags, with small tested examples in JavaScript and Python.