You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 \\d makes 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 (like 359123404V), but your regex checks for lowercase v, 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., abc123456789Vxyz would 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 uppercase V (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:43:00