How to limit "0" should not be placed at the first character in a textbox with jquery, how can I do that?
I want to limit "0", should not be placed in the first character in the textbox.
<div class="form-group row" align="center">
<label class="col-md-4 form-control-label"><span class="mandatory"></span> Payment</label>
<div class="col-md-8" >
<div class="input-group">
<input type="text" name="pay" id= "pay" class="form-control input-md" max="100000"/>
</div>
</div>
</div>
var myLength = $("#pay").val().length;
if($(this).val() === '0')
{
$(this).val('');
}
It limits the first digit to '0' but allows multiple 0's and another scenario is I start typing 10
after I have entered 0 before 00010
.
I only want to start without 0
.
+3
source to share
3 answers
It is best to use an event keyup
to prevent text from being entered 0
at the first position during user input.
Here's a Demo:
$('#pay').keyup(function(e){
if($(this).val().match(/^0/)){
$(this).val('');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" name="pay" id= "pay" class="form-control input-md" max="100000"/>
+2
source to share
To match a number that starts with any digit but not zero, use this regex:
^[1-9][0-9]*$
Example:
function validateInput(input) {
var regex = ^[1-9][0-9]*$;
return regex.test(input); // It will return true or false depends on the regex test
}
call this function with your input value.
+1
source to share