Javascript Approved Number in RegExp

This question already has an answer here:

  • Validate decimal numbers in JavaScript - IsNumeric() 48 answers

  • change your function to

    function myFunction()
    {
    var str = document.getElementById("number_field").value;
    var res = str.replace(/[^0-9.}]/g,"");
      if (res.indexOf('.') !== res.lastIndexOf('.')) {
        document.getElementById("approved_number").innerHTML="";
      } else {
       document.getElementById("approved_number").innerHTML=res;
      }
    }
    

    Example here:

    http://jsbin.com/UNOHoYek/1


    See http://jsbin.com/OKoJuloQ/3/ for a possible answer.

    Changing user input without providing feedback is probably not a good idea.

    Better to just handle what can be taken as a number and report the rest.

    window.alert is just one way to report it.

    The important bits are the conversion to Number and testing against NaN .

    CODE (also available via link above)

    <!DOCTYPE html>
    <html>
    <body>
    <input type="text" value="" id="number_field">
    <button onclick="myFunction()">Submit</button>
    <p id="approved_number"></p>
    <script>
      function myFunction() {
        try {
          var str = document.getElementById("number_field").value;
          // var res = str.replace(/[^0-9.}]/g,"");
          var res = str;
          if (Number.isNaN(Number(res))) {
            window.alert(res + " is not a number (NaN)nOnly digits, decimal point,nand exponent (e.g. 3.2e4) are allowed");
          } else {
            document.getElementById("approved_number").innerHTML=Number(res).toString(10);
          }
        } catch (exception) {
          window.alert(exception);
        }
      }
    </script>
    </body>
    </html>
    
    链接地址: http://www.djcxy.com/p/26414.html

    上一篇: HTML表单中的多个提交按钮

    下一篇: Javascript的批准号码在RegExp