Search code examples
c#htmlasp.net-mvcasp.net-corerazor

Limit @TexBoxFor digits to three and allow to type only numbers


I have the following control in razor:

@Html.TextBoxFor(model => model.Persons, new { @class = "form-control w100", id = "cantPersonasBloque", @type = "number", maxvalue="3"})

I want to limit the digits to three and allow only number. If I remove @type = "number" then maxvalue works and limits the digits to 3 but it's letting me add letters... However, if I put both together (type = number and maxvalue) it's limiting to number ok but not limiting the digits..

Is there a way to make both validations work? I did a lot of research and testing but I didn't find the solution yet.

Thanks


Solution

  • You can try to use type="text" with maxlength and regular expression:

    <input asp-for="Persons" class="form-control w100" id = "cantPersonasBloque" type="text" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="3" />
    

    result: enter image description here