Reputation: 59
I have code that will make sure that it only accept 3 numbers before the decimal and 3 numbers after decimal and one decimal only.
There is one scenario that it will not work.
Example:
if I type 12.123 then go back and type 12w.123, it will accept the "w" and remove the last number 3. It know its related with the JavaScript split.
Does anyone know how to fix this issue?
$('.numeric-decimal-63').on('input', function (event) {
var val = $(this).val();
var regex1 = new RegExp(/^(\d{1,3}|\d{0,3}\.\d{0,3})$/g);
var regex2 = regex1.test(val);
if (!regex2){
$(this).val(val.slice(0,-1));
}
});
Upvotes: 0
Views: 74
Reputation: 138267
$(this).val(val.slice(0,-1));
Will remove the last key, so "123w1" it removes the "1". You may want to go back to the previous state:
var state="0";
$('.numeric-decimal-63').on('input', function (event) {
var val = $(this).val();
var regex1 = new RegExp(/^(\d{1,3}|\d{0,3}\.\d{0,3})$/g);
if (!regex1.test(val) && val!==""){
$(this).val(state);
return;
}
state=val;
});
Upvotes: 0
Reputation: 324650
Absolutely positively never ever outright block user input. Here's why:
Let's say I'm typing away. 1, 3, w oops, finger slipped, no problem: ← Backspace, 2 there. Now let's see... huh? Why does the textbox only show 12
? Where'd my 3
go?
Instead, allow the user to type whatever they wish, and only after input has finished (ie. on change
event) should you validate the input and inform the user if it is non-compliant.
HTML5 does this for you:
<input type="number" min="0" max="999.999" step="0.001" />
Upvotes: 1