【发布时间】: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