ASP.NET MVC [RegularExpression] Attribute Not Functioning on Entire String Match

11,834

Solution 1

On the client side, the regex is executed by JavaScript, and JS doesn't support \A, \Z or \z. You could use ^ and $ instead, but you shouldn't need to. Regexes used in validators are usually anchored at both ends automatically. I'm pretty sure that's the case with ASP.NET MVC.

Solution 2

Use this instead: @"^\d{3,4}$"

^ - start of string.

$ - end of string.

Share:
11,834
GONeale
Author by

GONeale

Full time thinker. Overtime coder. Part time real world. Follow me on Twitter

Updated on June 04, 2022

Comments

  • GONeale
    GONeale almost 2 years

    I can't seem to find a similar topic on Stack Overflow regarding this, so here goes:

    Why is it when I specify against my ASP.NET MVC view model class the following definition:

    [Required]
    [RegularExpression(@"\A\d{3,4}\Z",
       ErrorMessage = "The security code (CVN) must be between 3 - 4 digits long.")]
    [Display(Name = "Card Security Code (CVN)")]
    public string CardCVN { get; set; }
    

    That on my unobtrusive client side validation test the regular expression cannot be validated? (and subsequently displays a form field error).

    It seems as soon as my regex is changed to [RegularExpression(@"\d{3,4}"... removing the entire string matching technique, it matches perfectly? and it seems the jquery validation that renders, even though it doesn't apply \A or \Z it matches only on entire string match anyway (doing what I originally needed!); Am I missing something?

    Thanks.

  • GONeale
    GONeale almost 13 years
    You missed the \ on \d. However thanks for the response. I will award Alan with the points as he explained his response though.
  • GONeale
    GONeale almost 13 years
    Thanks Alan. Interesting, one would imagine ASP.NET MVC truly should have converted it then :)