if your happy with your solution and you want just to allow one decimale you will have just add an extra line to check that, I use your code but I change keydown to keypress otherwise it wont work to catch the dot character, I added( ||($(this).val().split(".").length - 1 > 0 && String.fromCharCode(e.which) == '.') ) at the end of the code:
-the added code just check whether there is already a dot and if the pressed key is dot.
$("#" + fieldId).keypress(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190,110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ($("#" + fieldId).val().countDecimals() >=2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105 || ($(this).val().split(".").length - 1 > 0 && String.fromCharCode(e.which) == '.'))) {
e.preventDefault();
}
});
your way of doening it wont prevent a user from pasting a invalid content you you can prevent user from dat with this code:
$("#" + fieldId).bind('paste', function (e)
{
e.preventDefault();
});
I would advise you not to validate on kepress or keydown because of:
- user can type a dot after the number and leave the input (like 88. => not valid) which your code wont prevent(and can not otherwise the user can not type a decimale number).
- bij pressing many keys at the same time I was abel to get invalid characters in the input without preventing them.
-I would advise you to validate on blur so that the user get the freedom of editing and you can be sure of validating the real content of the input.