3

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

3
  • 3
    Use a grouping, (ABC|WXYZ)\w{8,9} Commented Feb 7, 2019 at 14:56
  • @Wiktor Stribiżew I can't believe it was that. Many thanks. Please add this as a solution so that I can accept it. And thanks for the lightening fast reply. Commented Feb 7, 2019 at 14:59
  • Posted below. I suggest using the non-capturing version, as best practice. Commented Feb 7, 2019 at 15:03

2 Answers 2

4

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}
^^^        ^
Sign up to request clarification or add additional context in comments.

Comments

1

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).

1 Comment

Thanks @canton7 for that explanation, very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.