-1

I need to check and make sure that a variable contains ONLY numerals 0-9 or a period or a comma. Anything else should be rejected.

I've set up a simple IF statement in a function that I thought would work but it's not:

function numCheck(source) {
  if (!(source.matches("[0-9.,]*"))) {
    alert('Number');
  }
  else {
    alert('Not a number');
  }
}

Nothing happens. I can call the function without the if statement and it works, but somehow I'm just not correctly doing the syntax.

4

4 回答 4

3

matches()不是标准库中的方法,但是,match()是。

事实上,你可能最好使用这样的东西......

var looksLikeANumber = /^[\d.,]+$/.test(source);

我之所以使用test(),是因为您不需要 的力量match(),这将返回捕获的组等。这样,您还可以source免费获得对字符串的隐式强制转换(如果传入了一个数字,那么您将遇到match()麻烦不上Number.prototype)。

于 2013-10-11T18:31:45.280 回答
1

您没有使用正则表达式分隔符和行开始/结束锚点。

它应该是:

source.match(/^[0-9.,]*$/)
于 2013-10-11T18:31:39.527 回答
0

试试这样

var match = /^[0-9.,]*$/.exec(this.value); // value to be matched
   if (!match) {
       alert('invalid');
   }
于 2013-10-11T18:33:57.873 回答
0

我会更进一步使用这个正则表达式并使用.test

var result = /^\d*[\d,.]\d*$/.test(string);

确保至少有一个数字(它可以接受更多)并且只有 1 个句点或 1 个点。

于 2013-10-11T18:39:04.230 回答