Javascript regular expression for negative Numbers with decimal

前端 未结 8 1304
感动是毒
感动是毒 2021-01-05 05:20

I want to test for this input: [an optional negative sign] 2 digits [an optional . and an optional digit] like this:

-34 or -34.5333 or

相关标签:
8条回答
  • 2021-01-05 06:04

    Try this regex:

    /^-?[0-9]{2}(?:\.[0-9]+)?$/
    
    0 讨论(0)
  • 2021-01-05 06:05

    This below simple html code will validate the +ve & -ve numbers of 2 digits plus optional minimum of 1 digit after decimal point.

    JS Code:

        function validateNum() {
            var patForReqdFld = /^(\-)?([\d]{2}(?:\.\d{1,})?)$/;
            var value = document.getElementById('txtNum').value;
    
            if(patForReqdFld.test(value)) {
                alert('Valid Number: ' + value);
            } else {
                alert('Invalid Number: ' + value);
            }
        }
    

    HTML Code:

        <label>Enter Number:&nbsp;</label>
        <input type="text" id="txtNum" onBlur="validateNum()"/>
    
    0 讨论(0)
提交回复
热议问题