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" })

Answers:

Answer

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>

Answer

if js validation is ok, you can do like:

$('form').on('keydown', '.digitfield', function (e) { -1 !== $.inArray(e.keyCode, [46, 8, 9, 27, 13]) || (/65|67|86|88/.test(e.keyCode) && (e.ctrlKey === true || e.metaKey === true)) && (!0 === e.ctrlKey || !0 === e.metaKey) || 35 <= e.keyCode && 40 >= e.keyCode || (e.shiftKey || 48 > e.keyCode || 57 < e.keyCode) && (96 > e.keyCode || 105 < e.keyCode) && e.preventDefault() });

and then add the digitfield class to textbox

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.