Search code examples
asp.net-mvc-3data-annotations

In Text box user cannot enter 15 digits continuously, mvc3


We have scenario where user cannot entered 15 continue numeric digits(i.e 411111111111111) in text box, so we have validate it using data annotations in mvc?


Solution

  • You can use a [ReqularExpression] attribute which will give both client and server side validation

    [RegularExpression(@"^((?!\d{15}).)*$)", ErrorMessage = "The value cannot contain 15 or more consecutive digits")]
    public string YourProperty { get; set; }
    

    The negative lookahead - (?!\d{15}) - specifies that if there are 15 (or more) consecutive digits, the match is discarded and its invalid.

    Refer RegExr for a more detailed description of the regex and some test cases (using 3 digits for simplicity).