![](/img/trans.png)
[英]Javascript Calculator: How can I create an operator button based on a condition?
[英]How can I validate calculator input in real time in JavaScript before passing it to operator (=) function?
两天来,我一直在尝试在我的 JavaScript 计算器中实时验证用户输入,然后再将整体输入传递给operator(=) 函数。 我想要实现的是:我不希望用户连续输入一个以上的运算符号或点。 当用户输入每个输入时,我希望计算器实时验证每个输入,这样如果用户连续输入多个操作符或点,计算器将警告用户并自动删除最后一个输入并更新验证的输入计算器屏幕。 例如;
1A) 22.3.2。 + 4 -6 **3 ++ 2-^ <-- 这是错误的(未验证)
1B) 22.3+4-6*3+2 <-- 这就是我想要的(已验证)
下面是我到目前为止编写的示例代码。
JavaScript
let userInput = "22.2. + 3 -4^"; //as the user is inputting, i want to be validating it in realtime
function validateWrongInput() {
let p = userInput;
for (i = 0; i < p.length; i++){
if ((p.charAt(i) === "!" || p.charAt(i) === "^" ||
p.charAt(i) === "*" || p.charAt(i) === "/" || p.charAt(i) === "+" ||
p.charAt(i) === "-" || p.charAt(i) === "(" || p.charAt(i) === ")") &&
(p.charAt(i - 1) === "!" || p.charAt(i - 1) === "^" ||
p.charAt(i - 1) === "*" || p.charAt(i - 1) === "/" ||
p.charAt(i - 1) === "+" || p.charAt(i - 1) === "-" ||
p.charAt(i - 1) === "(" || p.charAt(i - 1) === ")")) {
let a = p.split("");
a.pop();
let c = a.join("");
upDisplay.textContent = c; //This shows the user input as he is typing
updisplayResult = c;
downDisplay.textContent = "ERROR-Why Two Operators?"; // this shows the final result when the = sign is pressed
return true;
} else {
return false;
}
}
}
JavaScript
let userInput = "22.2. + 3 -4^"; //as the user is inputting, i want to be validating it in realtime
function validateDecimal() {
let p = userInput;
let pointCount = 0;
for (let i = 0; i < p.length; i++) {
if (p.charAt(i) !== "!" && p.charAt(i) !== "^" && p.charAt(i) !== "*" &&
p.charAt(i) !== "/" && p.charAt(i) !== "+" && p.charAt(i) !== "-") {
if (p.charAt(i) === "." && pointCount < 1) {
pointCount += 1
downDisplay.textContent = " ";
return "ok";
} else {
pointCount = 0;
let a = p.split("");
a.pop();
let c = a.join("");
upDisplay.textContent = c; //This shows the user input as he is typing
updisplayResult = c;
downDisplay.textContent = "ERROR-Why Two Operators?"; // this shows the final result when the = sign is pressed
return "ERROR-Why Two Operators?"+c;
}
} else {
pointCount = 0;
}
}
}
我正在寻找你的帮助。
const input = document.getElementById('userInput');
input.addEventListener('keydown', () => {
const p = input.value;
// validation...
})
听起来您正在寻找事件侦听器。 确保您有相应的 html input 元素,在这种情况下: <input type="text" id="userInput">
我相信最好让用户完成他们正在输入的任何内容并在之后检查。 这种行为可以通过使用事件侦听器blur
或在submit
事件期间提交时进行验证来实现(未解释,但您可以查找或询问)。
如果您一起制作正则表达式 (regEx),您可能会找到一种更好的方法来验证您的字符串。 这有点复杂,只有当您对它们有信心时才应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.