limit
limit

Reputation: 647

jQuery Validate only decimal number

Does anyone know how I can validate a price format like the following

1.00 1200.00, but I also want to allow as 1 and 1200

$.validator.addMethod('decimal', function(value, element) {
        return this.optional(element) || /^[0-9]+\.\d{1,3}$/.test(value);
    }, "Please enter a correct number, format 0.00");

jQuery.validator.setDefaults({
        debug: true,
        success: "valid"
    });

    $( "#myform" ).validate({
        rules: {
            field: {
                required: true,
                decimal: true
            }
        }
    });

^ I found this code, but it still allows commas. Basically I am looking for something like is numeric without the comma.

So basically only want to allow numbers and optional decimals.

Any suggestion?

Update: So the above works, but its forcing the requirement of decimal. How to make that optional so I can do 1200 or 1200.00? Or maybe there is a way to just convert 1200 to 1200.00 ?

Upvotes: 1

Views: 8314

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

My proposal to solve your problem is:

$.validator.addMethod('decimal', function(value, element) {
  return this.optional(element) || /^((\d+(\\.\d{0,2})?)|((\d*(\.\d{1,2}))))$/.test(value);
}, "Please enter a correct number, format 0.00");


$(function () {
  $("#frm").on('submit', function(e) {
    e.preventDefault();
    $('#log').text('Form is valid? ' + $(this).valid().toString());
  });

  $("#frm").validate({
    rules: {
      price: {
        required: true,
        decimal: true
      }
    }
  });
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>

<form id="frm">
    Money: <input name="price" id="price" type="text"><br>
    <input id="submit" type="submit" value="Submit">
</form>
<p id="log"></p>

Upvotes: 4

Related Questions