0

Hi I'm working now with form validation. How to make a regex for numbers, comma and decimals? Or in short for money value in textbox.

For example 12,100.10

jQuery(function($) {
    var validation_holder;

    $("form#register_form input[name='submit']").click(function() {

    var validation_holder = 0;

        var cost            = $("form#register_form input[name='n_unit_cost']").val();
        var cost_regex      = /^[0-9]+$/; // reg ex cost check  

        if(cost == "") {
            $("span.val_cost").html("This field is required.").addClass('validate');
            validation_holder = 1;
        } else {
            if(!cost_regex.test(cost)){ // if invalid phone
                $("span.val_cost").html("Integer Only is Allowed!").addClass('validate');
                validation_holder = 1;

            } else {
                $("span.val_cost").html("");
            }
        }
        if(validation_holder == 1) { // if have a field is blank, return false
            $("p.validate_msg").slideDown("fast");
            return false;
        }  validation_holder = 0; // else return true
        /* validation end */    
    }); // click end 

}); // jQuery End
surname
  • 163
  • 1
  • 1
  • 17
  • @theCoder I tried it but not works with me. http://stackoverflow.com/questions/1565994/regex-to-match-comma-separated-numbers-with-optional-decimal-part – surname Jan 24 '14 at 08:10
  • 1
    i once made a try an ran into dificulties, then i used numeral.js wich has a great support for various currencys and locales – john Smith Jan 24 '14 at 08:10
  • @surname next time try to use regex101 site to do your regex, it is very simple to use and very well done – Razorphyn Jan 24 '14 at 08:21

2 Answers2

0

Something like:

^\d{1,3}(?:,?\d{3})*\.\d\d$
Toto
  • 89,455
  • 62
  • 89
  • 125
0

Here's a regexp that'll satisfy you.

var cost_regex = ^\d+(,\d{3})*(\.\d+)?$

This will match numbers with or without commas, with or without digits.

Explanation : \d+ will match one or more digits. This will match numbers without commas. Then comes the (,\d{3})* part, which will allow the user to use commas every three digits, but will not match if there are commas in a stupid way in the number (for example, 1,,,2345 is not matched !). Then for the decimal part, (\.\d+)?$ will match a dot and any number of digits. The ? makes this part optional in the regex.

This tool is very handy to write and test regexs, I invite you to give it a try next time you want to validate a pattern !

Theox
  • 1,363
  • 9
  • 20