Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable zero as first letter in <input>

Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123 and putting 0. (or ctrl+a on input)

Is there a way to block this scenario?

 $('input#foo').keypress(function(e){ 
  if (this.value.length == 0 && e.which == 48 ){
   return false;
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />
like image 282
taesu Avatar asked Sep 16 '15 17:09

taesu


4 Answers

I would handle the input, propertychange, and paste events. Then use regex to match for anything that begins with 0 and replace the current value with the value minus the leading 0.

http://jsfiddle.net/SeanWessell/5qxwpv6h/

$('input ').on('input propertychange paste', function (e) {
    var val = $(this).val()
    var reg = /^0/gi;
    if (val.match(reg)) {
        $(this).val(val.replace(reg, ''));
    }
});

Bug fix reported by Kevin/Updated per recommendations of canon:

http://jsfiddle.net/SeanWessell/5qxwpv6h/2/

$('input').on('input propertychange paste', function (e) {
    var reg = /^0+/gi;
    if (this.value.match(reg)) {
        this.value = this.value.replace(reg, '');
    }
});
like image 69
Sean Wessell Avatar answered Nov 13 '22 20:11

Sean Wessell


I think you're looking for the keydown jQuery event as opposed to the keypress event. Here's some move info on the difference between the two. Try regex to get rid of leading zeroes:

$('input#foo').keydown(function(e){ 
    this.value = this.value.replace(/^0+/, '');
});
like image 2
zacran Avatar answered Nov 13 '22 22:11

zacran


Here's the fixed version :

<input id="foo" />

$('input#foo').keyup(function(e){ 
     if(this.value.substring(0,1) == "0")
     {
        this.value = this.value.replace(/^0+/g, '');             
     }         
});

jsfiddle : http://jsfiddle.net/ewmb1yq9/4/

like image 2
DinoMyte Avatar answered Nov 13 '22 22:11

DinoMyte


This could work:

$('input#foo').keyup(function(e) {
    if((this.value+'').match(/^0/)) {
        this.value = (this.value+'').replace(/^0+/g, '');
    }    
});

The only thing that could bother you with this solution is that zero is displayed for a second and then deleted, since we are using keyup event.

A quick demo

like image 2
keune Avatar answered Nov 13 '22 20:11

keune