Home > Net >  Length validation for int property
Length validation for int property

Time:12-30

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related