我使用 PHP 制作了这个随机数猜谜游戏,并且正在尝试使用 JavaScript 实现客户端表单验证。该脚本应该只允许 1-100 之间的数字,并拒绝其他所有内容,如空格、字母数字字符、负数和浮点数,和/或这些的混合。这是我到目前为止的脚本:
<script type="text/javascript">
//<![CDATA[
// The checkForm() function makes sure the user's guess is valid
function checkForm() {
var numericExpression = /[-+]?([0-9]*\.)?[0-9]+/; // Code is from regular-expressions.info
if (document.getElementById("userGuess").value.match(numericExpression)) {
return true;
} // ends the if statement
else {
alert("Enter a valid number between 1-100 that isn't negative or a decimal value");
document.getElementById("userGuess").focus();
return false;
} // ends the else statement
}
//]]>
</script>
这是表格:
<div id="container">
<h1 id="mainHeading">Let's play a game!</h1>
<h2 id="subHeading">I'm thinking of a number between 1-100. Take a guess on what you think it is.</h2>
<!-- User input -->
<form action="" method="post" onsubmit="return checkForm()" name="formGuess" id="formGuess">
<input type="text" name="userGuess" id="guessInput" />
<button type="submit" id="submit">You're probably going to get it wrong.</button>
</form>
</div> <!-- End container div -->
但它并没有按预期工作,它只拒绝纯字母输入。其他任何东西都混合在一起,脚本不起作用。我有网页上传到我的个人网站:PHP随机数游戏
谢谢!