验证文本字段中的数值不会产生所需的结果

时间:2013-08-26 04:13:02

标签: javascript regex validation

验证一个文本字段值,该值可能是正整数或数字,带有一个小数点和javascript中该点后的一个小数:

123
1
12345
233.2
1212.2
1.1

是有效数字和

1.222
1.33
-89789
-3

是无效的数字。

我已经应用了这个但没有得到理想的结果

  function CheckOneDecimal(txtbox) {
             if (txtbox.value.length > 0)
             {
                 if (isNaN(txtbox.value)) {
                     txtbox.value = "";
                     alert("Please enter number with one decimal places");
                     txtbox.focus();
                     return;
                 }
                 else if (parseFloat(txtbox.value) > 0)
                 {
                     txtbox.value = "";
                     alert("Please enter number with one decimal places. eg. 8.1");
                     txtbox.focus();
                     return;
                 }

                 var oRegExp = /^\s*\d+\.\d{1}\s*$/;
                   if (oRegExp.test(txtbox.value))
                     { }
                   else {

                         txtbox.value = "";
                         alert("Please enter number with one decimal places");
                         txtbox.focus();
                     }
               }
         }

2 个答案:

答案 0 :(得分:2)

这个正则表达式应该这样做:

/^\d*\.?\d$/

演示: http://jsbin.com/ovaVAfU/1/edit

答案 1 :(得分:0)

我会这样做:

/^\d+(?:\.\d)?$/

<强>解释

The regular expression:

(?-imsx:^\d+(?:\.\d)?$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
----------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \.                       '.'
----------------------------------------------------------------------
    \d                       digits (0-9)
----------------------------------------------------------------------
  )?                       end of grouping
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------