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


You can check it with a function charAt

if the line is:

var myLength = $("#pay").val();

        if(myLength.charAt(0) === '0')
        {               
            $(this).val('');
        }

      



A more useful way for an input field to not accept 0 as the first place.

Check working code: JS Fiddle

+1


source


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

Run codeHide result


+2


source


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







All Articles