9

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" />

7
  • you may wish to check out jQuery mask plugin Commented Sep 16, 2015 at 17:29
  • 3
    You still need server side validation, just as a reminder Commented Sep 16, 2015 at 17:34
  • 3
    the easy no-js way: <input pattern="^[^0]\d+"> Commented Sep 16, 2015 at 17:37
  • 1
    Seems like bad UX. If you type something into a textbox, you expect something to show up. Wouldn't it be better to just "santize" the data the user inputs and remove the leading zeros before persisting the data? Commented Sep 16, 2015 at 20:55
  • 1
    @pkr298: Or if we insist on using silly Web N.0 techniques, turn the input box red or something. Commented Sep 16, 2015 at 20:56

7 Answers 7

14

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, ''); } }); 
Sign up to request clarification or add additional context in comments.

5 Comments

All the other answers talking about key events are completely ignoring the issue specified in the question (dragging text inside input element). oninput event is the right way for this case.
Bug: Type 123000 and then delete 123. You're left with 00. I'd suggest using the regex ^0+.
@SeanWessell So, instead of updating your regex you've decided to reach for a while loop. On top of that, you're instantiating a new jQuery object for every single loop condition and its body. So, 1.: why are you using $(this).val() instead of this.value? It's unnecessary overhead. 2.: If you insist on $(this), why aren't you caching your jQuery objects? 3.: Why are you looping instead of just updating the regex? I'm worried over the fact that this answer has attracted so many upvotes.
@canon Updated answer. I use SO to learn from and help others and thank you for the pointers on how to write cleaner code!
While we're on the subject, you might consider RegExp.prototype.test() rather than String.prototype.match(). You're not really doing anything with the string value returned from match() other than banking on its truthy/falsey coerced value. test() simply returns true or false outright.
2

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+/, ''); }); 

1 Comment

this still allows you to enter a leading 0 it just won't allow anything after it. It also doesn't allow you to highlight and replace the text in the textbox. If you try it will append what you type to the string that was originally there.
2

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/

2 Comments

his completely disables 0 as input
you can hold 0 and it will result in 0000...
2

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

3 Comments

you can hold 0 and it will result in 000000..
it de-selects now. (ctrl+a)
updated once again, but the accepted answer is better.
1

Accept only numeric values not prefixed by zero. Supports Ctrl + A:

var escapeKeys = [8, 46]; $('input#foo').keyup(function (e) { if ($.inArray(e.keyCode, escapeKeys) != 0) { if ((this.value + String.fromCharCode(e.keyCode)).match(/^[1-9][0-9]*$|^$/) != null) { this.lastValidValue = this.value + String.fromCharCode(e.keyCode); } else if (this.lastValidValue) { this.value = this.lastValidValue; } else { this.value = ""; } } else { this.lastValidValue = this.value; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="foo" />

Comments

0

If you want to catch the changes to the input's value (including the changes made by dragging part of the text for example), you can watch the input event.

$('input#foo').on("input", function(){ alert($(this).val()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="foo" />

Comments

0

You could add a "submit" event to validate whether it's entered or not, regardless of how it could have gotten there:

$( "form" ).submit(function( event ) { if ( $( "input:first" ).val() != 0 ) { $( "span" ).text( "Validated..." ).show(); return; } $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 ); event.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <p>Type 'Anything but 0' to validate.</p> <form action="javascript:alert( 'success!' );"> <div> <input type="text"> <input type="submit"> </div> </form> <span></span> 

jQuery's working is example is last on page here (https://api.jquery.com/submit/)

NOTE: The most important part will be to add the "event.preventDefault()" action, because that will keep the form from accidentally submitting.

1 Comment

this answer is out of scope.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.