Search code examples
javascriptrazorhtml-helper

In Razor, accept whole number without decimal


I'm facing an issue with a textbox to only allow whole numeric value, not dot/decimal value in razor view. I looked around SO but unfortunately I can't find an answer.

JavaScript validation exists for accept numeric value with dot, but I want without dot/decimal.

cshtml:

@Html.TextBoxFor(Employee => Employee.AlternateNumber, new { @id = "txtAlternateNumber", @class = "form-control", @type = "number" })

Solution

  • This has nothing to do with razor, but rather html5, but adding step and min might help (depending on browser-support etc.):

    @Html.TextBoxFor(Employee => Employee.AlternateNumber, new { @id = "txtAlternateNumber", @class = "form-control", @type = "number", @step="1", @min="0" })
    

    A runnable example:

    <form>
    <input type="number" step="1" min="0"> <input type="submit">
    </form>

    For "realtime" checking, you have to use javascript:

    @Html.TextBoxFor(Employee => Employee.AlternateNumber, new { @id = "txtAlternateNumber", @class = "form-control", @type = "number", @step="1", @min="0", @onkeypress="return event.charCode >= 48 && event.charCode <= 57" })
    

    A runnable example:

    <form>
    <input type="number" step="1" min="0" onkeypress="return event.charCode >= 48 && event.charCode <= 57"> <input type="submit">
    </form>