简体   繁体   English

JavaScript正则表单表单验证失败

[英]JavaScript regex form validation failing

I made this random number guessing game using PHP, and I'm trying to implement client-side form validation using JavaScript. 我使用PHP制作了这个随机数猜测游戏,我正在尝试使用JavaScript实现客户端表单验证。 The script should allow only a number from 1-100 and reject everything else like whitespace, alphanumeric characters, negative numbers, and floating point numbers, and/or a mix of these. 该脚本应仅允许1-100的数字,并拒绝其他所有内容,如空格,字母数字字符,负数和浮点数,和/或这些的混合。 Here's the script I've got so far: 这是我到目前为止的脚本:

<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>

And here's the form: 这是表格:

<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 -->

It doesn't work as intended though, and it only rejects pure alphabetic input. 它虽然没有按预期工作,但它只拒绝纯字母输入。 Anything else mixed and the script doesn't work. 其他任何混合和脚本不起作用。 I have the web page uploaded to my personal website: PHP random number game 我将网页上传到我的个人网站: PHP随机数游戏

Thanks! 谢谢!

You don't need regex. 你不需要正则表达式。 To check if a variable is a number use: 要检查变量是否为数字,请使用:

var isNumber = (! isNaN(variable));

While I agree with the others that you don't really need a regex, in case you wanted to know how the regex should look like for a number (which is really a string since you're using regex) between 1 and 100, here is one way: /^[1-9]$|^[1-9][0-9]$|^100$/ 虽然我同意其他人你真的不需要一个正则表达式,如果你想知道正则表达式应该是什么样的数字(这是一个字符串,因为你正在使用正则表达式)在1到100之间,这里是一种方式: /^[1-9]$|^[1-9][0-9]$|^100$/

Let me know if that helps or if you have any questions :) 如果有帮助或者您有任何疑问,请告诉我:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM