MVC模型属性正则验证问题:NIC号码格式校验失败
Fixing NIC Number Validation in C#
Let's break down why your current regex isn't working, then fix it step by step.
What's Wrong with Your Current Regex?
Looking at [0-9]{11,11}\\d)|([0-9]{9,9}+v, there are several critical issues:
- Mismatched parentheses: You start with a closing
)before opening a(for the first group, which breaks the entire pattern. - Extra
\\d:[0-9]{11,11}already enforces 11 digits, adding\\dmakes it require 12 digits total—this is why you're seeing it only accept longer numeric inputs. - Incorrect quantifier:
+after[0-9]{9,9}is unnecessary (and invalid here) since{9}already means exactly 9 digits. - Case sensitivity: Your example uses an uppercase
V(like359123404V), but your regex checks for lowercasev, so it won't match valid uppercase entries. - Missing anchors: Without
^(start of string) and$(end of string), the regex could match valid patterns within longer, invalid strings (e.g.,abc123456789Vxyzwould be incorrectly accepted).
The Corrected Regular Expression
Here's the fixed regex that handles both your required formats:
^([0-9]{9}V|[0-9]{11})$
Let's break this down:
^= Start of the input string(= Start of a group to hold the two valid options[0-9]{9}V= Exactly 9 digits followed by an uppercaseV(matches your first format, e.g.,359123404V)|= Logical "OR" to separate the two valid formats[0-9]{11}= Exactly 11 digits (matches your second format)
)= End of the group$= End of the input string
If you want to accept both uppercase and lowercase V, modify it to:
^([0-9]{9}[vV]|[0-9]{11})$
Updated C# Code
Replace your current attribute with this:
[Display(Name = "NIC Number")] [Required] [RegularExpression(@"^([0-9]{9}V|[0-9]{11})$", ErrorMessage = "Please enter a valid NIC number (either 9 digits followed by V, or 11 digits).")] public string driverNic { get; set; }
Note the @ before the regex string—this avoids needing to escape backslashes, making the pattern easier to read.
Quick Test Cases
- Valid:
359123404V,12345678901 - Invalid:
359123404(missing V),1234567890(only 10 digits),359123404v(lowercase v if using the case-sensitive regex),abc123456789V(extra characters)
内容的提问来源于stack exchange,提问作者Binku
相关产品推荐
相关产品推荐

