Decimal or numeric values in regular expression validation

前端 未结 10 1271
礼貌的吻别
礼貌的吻别 2020-11-22 15:09

I am trying to use a regular expression validation to check for only decimal values or numeric values. But user enters numeric value, it don\'t be first digit \"0\"

10条回答
  •  粉色の甜心
    2020-11-22 15:40

    I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:

    function isNumber(v) {
      // [0-9]* Zero or more digits between 0 and 9  (This allows .25 to be considered valid.)
      // ()? Matches 0 or 1 things in the parentheses.  (Allows for an optional decimal point)
      // Decimal point escaped with \.
      // If a decimal point does exist, it must be followed by 1 or more digits [0-9]
      // \d and [0-9] are equivalent 
      // ^ and $ anchor the endpoints so tthe whole string must match.
      return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
    }
    

    Where my trim() method is

    String.prototype.trim = function() {
      return this.replace(/(^\s*|\s*$)/g, "");
    };
    

    Matthew DesVoigne

提交回复
热议问题