0

I'm trying to restrict 0 as first digit in input field. It works fine in macbook, but when user enter the amount in windows system the input field excepts the digit 0 and it is also not excepting the digit 9 as first digit, for eg: 9845 but it excepting like 8945. Below is the code.

I am just getting confused as where the bug is. It would be great if anyone can help me out with this:

JS CODE:

$("#stamp_amount").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A, Command+A (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return; } if ( event.keyCode == 46 || event.keyCode == 8) { // let it happen, don't do anything } else { // Ensure that it is a number and stop the keypress if ((event.keyCode !==9) && (event.keyCode < 48 || event.keyCode > 57 )) { event.preventDefault(); } else{ if($.trim($(this).val()) =='') { if(event.keyCode == 48 || event.keyCode == 57 || event.keyCode == 96 || event.keyCode == 105){ event.preventDefault(); } } } } }); 

1 Answer 1

1

Instead of checking what key was pressed check input value itself.

Regex /^0|[^0-9.]/ means starts with 0 or contains character other than numbers and .

$(document).ready(function() { $('#inp').change(function() { if ($(this).val().length == 0 || /^0|[^0-9.]/.test($(this).val())) { $('#valid').removeClass('valid'); } else { $('#valid').addClass('valid'); } // make input valid $(this).val($(this).val().replace(/^0+|[^0-9.]+/, '')); }); })
#valid:after { content: "No"; color: red; font-weight: bold; } #valid.valid:after { content: "Yes"; color: green; font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="inp" placeholder="51.54" />Eur <br/> <span id="valid"></span>

Sign up to request clarification or add additional context in comments.

4 Comments

Justinas it's excepting alphabets I don't want that to happen
@PreetySingh So regex [^0-9.]+ will match anything that is not number or dot and that way you filter for letters.
is there any other way to implement because this is not accurate according to the current scenario.
your answer was useful I did little bit modification with my code and included this line in my code: $(this).val($(this).val().replace(/^0+|[^0-9.]+/, '')); and it worked like I wanted. Now I just have to give an error message if the user types 0 as first digit. Thank you so much :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.