Javascript function need allow numbers, dot and comma

前端 未结 6 1950
悲&欢浪女
悲&欢浪女 2020-12-09 04:30

I need to create a function to allow numbers dot and comma. So anyone corrects the following function

function on(evt) {
  var theEvent = evt || window.event         


        
相关标签:
6条回答
  • 2020-12-09 05:10

    Firstly your regex currently doesn't allow comma, which is your requirement.

    Secondly, you haven't used any quantifier, so your regex will match only a single character - one of [0-9] or a dot. You need to use a quantifier.

    Thirdly, instead of using pipe, you can move all characters inside the character class only.

    Try using the below regex:

    /^[0-9.,]+$/
    

    Quantifier + is used to match 1 or more occurrence of the pattern.
    ^ and $ anchors match the beginning, and end of the string respectively.

    0 讨论(0)
  • 2020-12-09 05:11

    Sometimes /^[0-9.,]+$/ is not work If not, then you could do something like this:

    /^(?:[\d-]*,?[\d-]*\.?[\d-]*|[\d-]*\.[\d-]*,[\d-]*)$/
    
    0 讨论(0)
  • 2020-12-09 05:12

    The Regex that I made for numbers following format of COMMA9.2

    Example

    1. 1,350.88
    2. 120.00
    3. 1,500,999.24
    4. 100
    5. 10000000

    RegEx

    ^(\d+|\d{1,3},\d{3}|\d{1,3},\d{3},\d{3}|\d{1,3}(,\d{3})*|\d{1,3}(,\d{3})*\.\d+)$

    0 讨论(0)
  • 2020-12-09 05:16

    This is the best solution, in my opinion, covers more cases of inputs and allow floats.

         $( ".numerical" ).on('input', function() { 
                    var value=$(this).val().replace(/[^0-9.,]*/g, '');
                    value=value.replace(/\.{2,}/g, '.');
                    value=value.replace(/\.,/g, ',');
                    value=value.replace(/\,\./g, ',');
                    value=value.replace(/\,{2,}/g, ',');
                    value=value.replace(/\.[0-9]+\./g, '.');
                    $(this).val(value)
    
            });
    
    0 讨论(0)
  • 2020-12-09 05:31

    No need for JavaScript:

    <input type="text" pattern="[0-9.,]+" title="Please enter a valid decimal number." />
    

    Modern browsers will handle this perfectly.

    If you want to specifically allow commas as thousand separators and a single decimal point, try this:

    ... pattern="\d{1,2}(,\d{3})*(\.\d+)?" ...
    

    Note that I am firmly against blocking user input. They should be able to type what they want, and then told if they enter something invalid.

    0 讨论(0)
  • 2020-12-09 05:34

    Your regex is incorrect.

    var regex = /^[0-9.,]+$/;
    

    Regex javascript, why dot and comma are matching for \

    https://stackoverflow.com/tags/regex/info

    0 讨论(0)
提交回复
热议问题