Reputation: 148534
I build a mechnism using JS for accepting only digits :
However I want to allow : Delete, Backspace , left arrow , right arrow :
the solution I came up with is :
assuming I write in html (which I know its bad to send event , but lets focus on the Js code please) :
<input onKeyPress='return CheckDigit(event)'/>
function CheckDigit(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= 48) && (charCode <= 57)) || checkIfDelOrNavigate(charCode)))
return true;
return false;
}
function checkIfDelOrNavigate(c)
{
if (((c == 46) || (c == 39) || (c == 37) || (c == 8))) return true;return false;
/*46=delete , 39,37 = arrows , 8=backspace*/
}
Questions :
Is it the right solution ? (and if it ain't , can you please supply an answer)
I assume it can be changed to regex checking :
code:
var regEx =/^[0-9]+$/;
isValid = regEx.test(keyChar);
return isValid;
But what will be the full regEx
expression ?
p.s. : Strange but all the solutions I saw doesnt want to allow the Delete, Backspace , left arrow , right arrow chars , just the category itself.
Upvotes: 3
Views: 273
Reputation: 1252
I combine the answer to this question with the following check to make sure I only capture digits while allowing for non-printable characters. You'll have to do something about the paste operation, though.
return !window.isNaN(String.fromCharCode(event.which))
See jsFiddle.
Upvotes: 3