I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46 && el.value.indexOf(".") !== -1) {
return false;
}
if (el.value.indexOf(".") !== -1)
{
var range = document.selection.createRange();
if (range.text != ""){
}
else
{
var number = el.value.split('.');
if (number.length == 2 && number[1].length > 1)
return false;
}
}
return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>
The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are
a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335
b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.
Can you tell me what could be the issue?
Thanks,
Jollyguy
Consider leveraging HTML5's Constraint Validation API. I doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the
<form>
(by default). I added the<output>
to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.