Durga
Durga

Reputation: 565

How to stop 0 doesn't allow of first character in some scenarios by using jquery

I am new to jquery. I have form with two text boxes. In that i am restrict special characters.

Now i want stop 0 in some cases.

valid and invalid scenarios:

000 - invalid

01 or 0100- invalid

100 - valid

0.44- valid

0.00 - invalid

$('#minAmt').bind('paste', function() {
  var self = this;
  setTimeout(function() {
    if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
  }, 0);
});
$('.minAmt').keypress(function(e) {
  var character = String.fromCharCode(e.keyCode)
  var newValue = this.value + character;
  if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
    e.preventDefault();
    return false;
  }
});

function hasDecimalPlace(value, x) {
  var pointIndex = value.indexOf('.');
  return pointIndex >= 0 && pointIndex < value.length - x;
}
$('#maxAmt').bind('paste', function() {

  var self = this;
  setTimeout(function() {
    if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
  }, 0);
});
$('.minAmt').keypress(function(e) {
  var character = String.fromCharCode(e.keyCode)
  var newValue = this.value + character;
  if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
    e.preventDefault();
    return false;
  }
});

function hasDecimalPlace(value, x) {
  var pointIndex = value.indexOf('.');
  return pointIndex >= 0 && pointIndex < value.length - x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <div class="col-md-6">
    <div class="form-group ">
      <label for="minAmt" class="col-lg-4 control-label">Min.Amount</label>
      <div class="col-lg-6">
        <input type="text" class="form-control minAmt" id="minAmt" name="minAmt" placeholder="Enter Min Amount" />
      </div>
    </div>
    <div class="form-group ">
      <label for="maxAmt" class="col-lg-4 control-label">Max.Amount</label>
      <div class="col-lg-6">
        <input type="text" class="form-control maxAmt" id="maxAmt" name="maxAmt" placeholder="Enter Max Amount" />
      </div>
    </div>
  </div>
</form>

Upvotes: 0

Views: 77

Answers (1)

Thennarasan
Thennarasan

Reputation: 718

Hope your requirement is : value is invalid if it starts with 0 and also if it starts with 0 after the decimal.

As per your request

000 - invalid
01 or 0100- invalid
100 - valid
0.44- valid
0.00 - invalid

Use this regex,

^([1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$ 

You will get the output as

100 - valid
0.44- valid

Upvotes: 1

Related Questions