2

I can input

0 but not 0123. How do I prevent users not to input 0 at the first position of the input text field?

mengmeng
  • 1,266
  • 2
  • 22
  • 46

2 Answers2

5

Let them input it, just trim it when focus changes:

inputElement.onblur = function() {
  this.value = this.value.replace(/^0+(?=\d)/,'');
}

Fiddle

Note that it's specifically looking for a digit (\d) after the 0's that it's nuking, so it won't touch the zero in something like 0.123. If you want to get rid of those, too, just change the \d to ., which matches any character whatsoever.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

One way to do this is to check the first character in the input using charAt().

Demo

JS:

function check(){
    var number = document.getElementById('input').value;
    if(number.charAt(0) === 0)
        alert('Leading zero in the input.')
    else
        alert('No leading zero in the input.')
}

EASIER SOLUTION:

For the input, just check the first character like an array:

if(number[0] === '0')
        // do something

Demo

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138