Anne Anne - 1 year ago 117
Javascript Question

Restrict zero in a numeric only input field

This is my code and it it allows to enter digits only. How do I restrict from entering zero (0) as the first digit?

$('.btn').keypress(function(e) {
var code = e.which;
if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 8) || (code >= 48 && code <= 57)){
return true;
return false;
.bind('paste',function(e) {

Answer Source

Doing such work requires quite a bit of advance JavaScript.

First you need to know whether the cursor / caret is in position 0. To do that you need to get the selection range. That varies depending on the browser you are using.

Code snippet (untested) for Firefox & SeaMonkey:

var range = document.createRange();
var pos = range.startOffset;

Then if pos is zero, you know the cursor is at the start and you can test whether the user pressed zero:

if(pos == 0 && code == 48)

However, you want to also think about the case where the user enters 100 and put his cursor or selection to include the 1 or 10. Now he hits delete and what's left is one zero (0). How to handle that case will very much depend on what you really want to offer in your UI. I have seem really annoying systems that would auto-delete the rest of the text because it does not match a valid answer, not giving you a way to fix it... I do believe that's not a good solution.

Another solution, which is what I generally do, is to let the user enter whatever in the field (well, in your case, allow for digits only, but any random number), then when the user clicks "Submit", then you verify the format. If the format is wrong, barf out an error. In that case, the comment about regex's by Mate applies well (although he did not explain anything in his comment, kindda sad).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download