In web development, validating user input is crucial, especially when it involves personal identification information. The Chinese ID card number is a unique identifier for citizens and follows a specific structural pattern. Using PHP regular expressions to validate ID card numbers can effectively improve data accuracy and application security.
A Chinese ID card number typically contains 18 characters. The first six digits represent the administrative region code, digits 7 to 14 indicate the date of birth (formatted as YYYYMMDD), digits 15 to 17 are sequence codes, and the last digit is a checksum, which may be a number or the letter X. These fixed rules allow regular expressions to determine whether an ID number is valid.
The following PHP example demonstrates how to use a regular expression to check whether an ID card number is formatted correctly:
<?php
// Define the regular expression for ID card number
$idCardPattern = '/^([1-9]\d{5})(18|19|20)\d{2}(0[1-9]|1[0-2])([0-2]\d|3[01])\d{3}([0-9X])$/';
// The ID card number to validate
$idCardNumber = '123456199001012345';
// Use preg_match to perform the match
if (preg_match($idCardPattern, $idCardNumber)) {
echo "The ID card number format is correct.";
} else {
echo "The ID card number format is incorrect.";
}
?>In this example, we first define a regular expression pattern $idCardPattern to describe the structure of a valid ID number. Then, we assign an example ID card number to $idCardNumber and use preg_match() to check for a match, outputting a message based on the result.
The regular expression checks multiple aspects of the ID card number:
This validation method effectively filters out invalid or improperly formatted ID numbers before submission.
Developers can apply this method in features such as user registration, real-name authentication, and personal data submission. Combining front-end validation with PHP server-side checks greatly enhances data reliability and system security. For more comprehensive validation, developers are encouraged to integrate checksum algorithms for ID numbers as well.
This article provided a detailed explanation and PHP code example for verifying Chinese ID card numbers using regular expressions. By implementing this approach, developers can efficiently ensure correct ID formats and strengthen data validation within their applications.