-1

I am trying to stop the user being able to enter a 0 as the first number.

This is the code I have atm

function validate_numberonly(evt)
{
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        theEvent.preventDefault();
    } 
}

The regex to allow this is replace(/[^0-9]/g,''); But entering this instead of the current regex doesn't seem to work

joshuahornby10
  • 4,222
  • 8
  • 36
  • 52
  • and it shouldn't work, because logically that doesn't do what you want. – Kevin B Nov 12 '13 at 20:01
  • That code is preventing anything that does not match the regex through, key by key, with no regard to what has come before. Preventing just the first character is a different matter. – Orbling Nov 12 '13 at 20:01
  • possible duplicate of [Replace leading 0 on input field](http://stackoverflow.com/questions/19935832/replace-leading-0-on-input-field) – Ωmega Nov 12 '13 at 20:03
  • Replacing the first digit would be `replace(/^[0-9]/,'');`. Note the carrot position outside the brackets. – woemler Nov 12 '13 at 20:04
  • 1
    Consider simply validating the overall content of the field and displaying an error message (preventing submission until the error is resolved) rather than messing with a user's keyboard input - it can be disconcerting to the user, making them wonder why their keypress isn't working. It's also a lot simpler than trying to deal with various scenarios for keypresses that should or shouldn't be allowed in various contexts. – Amber Nov 12 '13 at 20:06
  • are you allowing zero? if so, you could just cast to int, cast back to string, and use the result as the value. it's not clear to me what your use case is though. – Corley Brigman Nov 12 '13 at 20:07
  • The first number can not be 0, after that they can enter a zero. – joshuahornby10 Nov 12 '13 at 20:13
  • Let's hope for the best! `$('input').on('keyup keypress', function(){if($(this).val().substring(0, 1) == '0'){$(this).val($(this).val().substring(1, $(this).val().length));}});` http://jsfiddle.net/Dg53w/ – MonkeyZeus Nov 12 '13 at 20:16
  • For the record, I agree with @Amber . . . it's better to check the whole value and provide a helpful error message, than to block keystrokes. – talemyn Nov 12 '13 at 20:20

4 Answers4

2

Try this:

/^[1-9]\d*$/

This check would make sure that the first character was any digit but "0", followed by zero or more of any digit.

This pattern requires a slightly different approach from what you have. Instead of examining the key value, you want to do the test against the entire field value. If the current key press breaks the pattern match, it will block the associated character from being added to the value.

Only keystrokes that add a character that continues to match the pattern will be allowed to be added. In this case the pattern breaks down to:

  • ^ - beginning of the value
  • [1-9] - exactly one character, only the digits 1 through 9 are allowed
  • \d* - zero or more of any digit (i.e., 0 through 9)
  • $ - end of the value

UPDATE:

Now that I've seen how you are binding it, you should be able to make a couple of updates to make it work. First, you need to pass the element that the validation is bound to. . . so, in your HTML, change this:

onkeypress='validate_numberonly(event)'

. . . to this:

onkeypress='validate_numberonly(this, event)'

Then, in your JS, you need to make two changes: 1) accept the new parameter, and 2) retrieve the value of the input and make it part of the regex chek:

function validate_numberonly(evt) {
    . . .
if( !regex.test(key) ) {
    . . .

. . . becomes, this:

function validate_numberonly(el, evt) {
    . . .
if( !regex.test(el.value + key) ) {
    . . .

Now, the code will only except number values that create a value that matches the regex pattern.

That being said . . .

This also blocks ALL non numeric characters . . . including "Backspace" and "Delete" (not to mention, the arrow key, "Home", "End", etc.), meaning that the user can no longer change a value, once they have entered it, without using the right-click menu of their mouse (or adding additional validation to allow those control key values that you want to still function).

It really would make much more sense to use the regex that I provided as a "final value" check that is triggered by the onchange event, and provide an error message of some sort, prompting the user to enter only digits, with no leading "0"s.

talemyn
  • 7,822
  • 4
  • 31
  • 52
  • This stops them entering a 0 first but then doesn't allow them to enter a zero later on? – joshuahornby10 Nov 12 '13 at 20:05
  • No, what this pattern does is lets you know if the entire field value has broken the "no leading zeros" rule. You would test the entire field value, rather than just the keystroke. If the check failed, then you would block the newest character from being added. – talemyn Nov 12 '13 at 20:10
  • I understand the logic, but this doesn't allow me to enter a 0 at all. I want to be able to enter a zero after the first character. – joshuahornby10 Nov 12 '13 at 20:19
  • Sure it does . . . the `[1-9]` represents only the first character of the value. The `\d*` allows for any digit (i.e., 0 through 9), in any position AFTER the first character. – talemyn Nov 12 '13 at 20:40
  • I'm afraid it doesn't. I can not enter another zero in my input box. – joshuahornby10 Nov 12 '13 at 20:53
  • Can you show your current JS code? Specifically, the updated validation method and how the input is being bound to it? It could be that we need to make some changes there . . . the regex itself, should match the restrictions that you described. – talemyn Nov 12 '13 at 21:22
1

You may try this without regex also like this:

$('input').keypress(function(e){ 
   if (this.value.length == 0 && e.which == 48 ){
      return false;
   }
});

This will not allow user to enter zero as first number.

JSFIDDLE

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 2
    What if the user selects the entire content and then presses '0'. – Vatev Nov 12 '13 at 20:02
  • This also fails if you type something, they go back and press 0. – Tim Meers Nov 12 '13 at 20:04
  • @Vatev:- Yes then it wont work. But I concentrated here: `I am trying to stop the user being able to enter a 0 as the first number.` – Rahul Tripathi Nov 12 '13 at 20:04
  • Or if they enter `x0` and then delete the `x`. – James Montagne Nov 12 '13 at 20:04
  • It is extremely difficult (maybe impossible) to cover all cases which will end up as '0xx'. Let the poor users type as much zeroes as they want and just ignore/remove them later. – Vatev Nov 12 '13 at 20:10
  • @Vatev:- Yes you are correct. I am not very sure(so correct me if I am wrong) but can we disable the user to select all the text at once and delete it. Instead delete it using the backspace? – Rahul Tripathi Nov 12 '13 at 20:10
  • You probably can, but the result will look more like a bug than a feature. – Vatev Nov 12 '13 at 20:19
0

Have you tried reading the keypress ascii value and testing?

Say, something like;

//when key is pressed in the textbox$("#quantity").keypress(function (e)
{
  //if the letter is not digit then display error and don't type anything
   if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
   {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;

} });

Adjusting the above example to detect the '0' ascii character code may be simpler to using regex. You could test for the current text box string length and exit the function if it's greater than 1.

Code sample from: http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

Nick
  • 3
  • 2
0

For the record this worked

<input type="text" onblur="this.value=this.value.replace(/^0+/, '')">
joshuahornby10
  • 4,222
  • 8
  • 36
  • 52