skip to Main Content

Is there any validation for integers where user can write only exact length of integer.

There is [Range] but that works only for range of value.
There is also [MaxLength] and [MinLength] for string but is there something like that for integers.

I need property that has type int but which allows to enter exactly 11 numbers.
I think one option is [Range(10000000000, 99999999999)], but that is awful.

2

Answers


  1. Change the type to a string and use a simple Regex of ^d{11}$. Otherwise you could build your own validator.

    Login or Signup to reply.
  2. you can use a textbox which can just typed numbers

    in jquery side you can write

    $("#txtNumberField").keypress(function (e) {
        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
    

    in cshtml side you can write like this

    @(Html.TextBoxFor(m => m.NumberField).HtmlAttributes(new { @Id = "txtNumberField", style = "width:100%", maxlength = "10", required = "required", validationMessage = "Enter Number" }))
    

    max length is 10 because max int value is 2,147,483,647

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search