【问题标题】:Number validation for JavaScript simple calculator with RegEx使用 RegEx 对 JavaScript 简单计算器进行数字验证
【发布时间】:2017-12-04 21:11:26
【问题描述】:

我正在用 HTML、CSS 和 JavaScript 制作一个简单的计算器。必须使用正则表达式验证输入字段以仅接受数字和数学符号 + - * / 。

这是 HTML 代码中的输入字段:

<input type="text" name="answer" id="answer-field" oninput="checking()" /> 

这是 JavaScript 函数检查():

function checking(){
  var x = document.calculator.answer.value;  // the value of the input field
  var regex=/[0-9]\b/;  // my failing regex 
    if (x.match(regex) || (x==="+") || (x==="-") || (x==="*") || (x==="/"))
    {
      document.getElementById("problemWithInputMessage").innerHTML="";
      console.log("true, it IS a number");
      return true;
    }
    else if(!(x.match(regex))){
      console.log("false, not a number");
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1);   // removing the wrong symbol
      document.calculator.answer.value = x;
      return false;
    }
}

问题是多方面的。对于初学者来说,正则表达式不能正常工作,因为它只搜索输入字符串的开头和结尾。此外,还有一些不同于 +-*/ 的符号。请留在输入字段内,不要被排除在外。

您能帮我正确验证数字和符号 +-*/ 的输入字段吗?只有?

【问题讨论】:

  • 可能是那个“字边界”\b 在那里,不应该只是[0-9]+ 来检测(一个或多个)数字吗?
  • 不,它根本不起作用。我尝试添加+,然后尝试+$,虽然我没有得到它,而不是\b,但问题仍然存在。唯一的区别是现在它不会接受任何符号,甚至我需要的那些 +-*/.

标签: javascript html regex validation numeric


【解决方案1】:

我最终提交了这个代码:

function checking() {
  var x = document.calculator.answer.value;
  document.getElementById("problemWithInputMessage").innerHTML="";
    var regexNumbers = /[0-9]+$/;                       //Regular Expression for the numbers
    var regexSigns = new RegExp(/[\+\-\/\*]+$/g);       //Regular Expression for the Special Signs

    if(x.match(regexSigns) || x.match(regexNumbers)) {  //checking for Numbers and the Special allowed signs
        return true;
    }
    else {
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1); //Deleting the last symbol if it is not allowed
      document.calculator.answer.value = x;
      return false;
    }
}

我用 2 个不同的正则表达式将 2 个任务分开。第一个

/[0-9]+$/

只检查数字,第二个

/[+-/*]+$/g

检查特殊符号 +-/* (虽然我忘了加上点。)感谢您的回答,它帮助了很多:)

它不是 100% 的,因为如果你在字符串的后面键入它就可以了,但是如果你把光标放在你输入的数字字符串中,它仍然允许你输入字母和其他符号在中间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2015-06-25
    相关资源
    最近更新 更多