Search code examples
asp.netasp.net-mvcentity-frameworkvalidationef-database-first

regular expression to validate MVC model property


I need a way to validate these

9 numeric values + V ==> 359123404V or 11 only numeric values 199245781248

i tried below code

[Display(Name = "NIC Number")]
[Required]
[RegularExpression("[0-9]{11,11}\\d)|([0-9]{9,9}+v")]
public string driverNic { get; set; }

dose not work

weirdly enough this validates only 13 numeric char input


Solution

  • The correct regex for your case is (^[0-9]{11,11}$)|(^[0-9]{9,9}V$).

    For a full explanation, see regex101.com. Note that this assumes that the "V" is always uppercase.

    Also see this C# Fiddle for some test cases.