简体   繁体   中英

Regular Expression problem (in asp.net MVC5)

hoping someone can point out what I'm missing here with a regular expression.

Here is the data item from my model :-

[Display(Name = "Serial to Search")]
[MaxLength(12)]
[RegularExpression(@"ABC|WXYZ\w{8,9}")]
public string SerialNo { get; set; }

This should allow me to match a serial that begins with either ABC or WXYZ and has another 8 or 9 characters/numbers.

In my view I'm using jquery unobtrusive validation and an @Html.ValidationMessageFor control to display errors.

I have tested this on regex101.com using the following test string :-

ABCGC1000BC5

and it passes fine, but in my view I get a validation error, specifically that the string doesn't match the regex requirements. Can anyone see what I'm missing ? Thanks.

regex101.com screenshot

Your regex matches two type of strings: 1) ABC or 2) WXYZ followed with 8 or 9 word chars. Remember that RegularExpressionAttribute pattern must match the whole string. Even if regex101.com shows a match for ABC12 , it won't match in your environment.

You need to use a grouping,

(ABC|WXYZ)\w{8,9}
^        ^

A non-capturing group would fit even better since you are only validating a string and not using captures later:

(?:ABC|WXYZ)\w{8,9}
^^^        ^

RegularExpressionAttribute searches for an exact match: if the Regex isn't anchored to beginning or end of the string, then RegularExpressionAttribute will effectively do that anchoring for you. See the implementation on ReferenceSource .

That is the difference between regex101.com and your test where it fails. If you anchor the regex on regex101.com, as ^ABC|WXYZ\\w{8,9}$ , you will see that it fails.

The reason, as Wiktor Stribiżew pointed out in the comments, is that your regex looks for ABC OR WXYZ\\w{8,9} . Neither ^ABC$ nor ^WXYZ\\w{8,9}$ match your test string of ABCGC1000BC5 .

Edit: (Please accept Wiktor Stribiżew's answer as the solution. This answer just aims to explain the difference between running it on regex101.com and in ASP.NET).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM