简体   繁体   中英

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

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

Let me know if that helps or if you have any questions :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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