1

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 ?

limit
  • 647
  • 2
  • 8
  • 27
  • Delete the comma from that `[ ]` part of the regular expression. – Pointy Mar 15 '16 at 23:35
  • Also [see this question](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric?rq=1), which for me at least is at the top of the "Related" section over there ========> – Pointy Mar 15 '16 at 23:37
  • Removing the comma worked. Yeah i saw the isNumeric(), but not exactly sure how to tie into $.validator. I want to also make sure that just digits can be entered so 1200 or 1200.00 – limit Mar 15 '16 at 23:44
  • You can make the decimal part optional by `(?:\.\d{1,3})?`. Note that you won't match any negative number. – Sebastian Proske Mar 15 '16 at 23:48

1 Answers1

4

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61