0

I am using DataAnnotations in MVC for validation of PAN card number. If I Check my expression online on https://regex101.com/, it execute correctly. But when I am trying it in my application, it gives error message as shown in below image.

enter image description here

I don't understand why this fails. Well I have used following code to implement this in model. So how can I implement it?

[DisplayName("PAN Number")]
[Required(ErrorMessage = "* Please Enter PAN No.")]
[RegularExpression(@"/[A-Z]{5}\d{4}[A-Z]{1}/", ErrorMessage = "* Invalid PAN Number")]
public string US_PAN { get; set; }
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
SVT002
  • 51
  • 3
  • 9
  • 1
    Add `anchors`, your regex becomes `/^[A-Z]{5}\d{4}[A-Z]$/`. And you don't need `{1}` in last `[A-Z]` as it itself matches single letter. –  Feb 03 '16 at 14:33
  • @noob: It is a RegularExpressionAttribute, the pattern is anchored by default (the pattern should match the whole input). – Wiktor Stribiżew Feb 03 '16 at 14:34

1 Answers1

0

Regular expressions in .NET doesn't need to be enclosed into // pairs.

regex101 by default uses php-like style of regular expressions - that's why it requires regex enclosing with //.

So your attribute should be just

[RegularExpression(@"[A-Z]{5}\d{4}[A-Z]{1}", ErrorMessage = "* Invalid PAN Number")]
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • 1
    Why explain what is already explained? http://stackoverflow.com/questions/31560080/removing-all-non-word-characters-with-regex – Wiktor Stribiżew Feb 03 '16 at 14:33
  • 1
    @WiktorStribiżew Can you suggest some search query based on original question content that will show answer you're mentioned? Something like "c# regex delimiters" doesn't succeed and I think it is almost impossible to find it for anyone except answer's author – Andrey Korneyev Feb 03 '16 at 14:40
  • I know, I could not find one. But this issue is 1) frequent, 2) more like a typo issue than a real issue, 3) evident to any C# programmer who used regex at least once. I close such questions as dupes (I keep a list). Such questions like this one will not ask "why my pattern with regex delimiters does not work" because question authors do not know what regex delimiters are, so it is really difficult to find one using a search system on SO/Google. I edited the title of the question I used as the original so that it could be found easier using a search engine. – Wiktor Stribiżew Feb 03 '16 at 14:46