Sooraj Abbasi Sooraj Abbasi - 23 days ago 13
Javascript Question

How prevent user to enter Zero as first digit in html input box using jquery Validation plug-in,

I am working on validation of HTML form using J query Validate plugin, I am want to restrict things so that the user cannot enter zero as first digit.

For example: I have a text box to enter Amount for any item so user can not enter zero as amount.

sam sam
Answer

You can perform a custom validation by adding your own validator using addMethod

As you want to restrict the user from entering 0 as a first digit in the text field, it can be achieved using regular expression ^[^0]\d*.

Here is a snippet.

$.validator.addMethod("pattern", function(value, element, regexpr) {
  return regexpr.test(value);
}, "Please enter a valid value.");

$("form").validate({
  rules: {
    cost: {
      required: true,
      //change regexp to suit your needs
      pattern: /^[^0]\d*$/g
    }
  }
});
.form-group label.error {
  color: maroon;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://jqueryvalidation.org/files/dist/jquery.validate.js"></script>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

  <title>JS Bin</title>
</head>

<body>
  <form class="form-inline">
    <div class="form-group">
      <label for="cost">Cost:</span>
        <input class="form-control" id="cost" type="number" name="cost">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</body>

</html>