簡體   English   中英

JavaScript正則表單表單驗證失敗

[英]JavaScript regex form validation failing

我使用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隨機數游戲

謝謝!

你不需要正則表達式。 要檢查變量是否為數字,請使用:

var isNumber = (! isNaN(variable));

雖然我同意其他人你真的不需要一個正則表達式,如果你想知道正則表達式應該是什么樣的數字(這是一個字符串,因為你正在使用正則表達式)在1到100之間,這里是一種方式: /^[1-9]$|^[1-9][0-9]$|^100$/

如果有幫助或者您有任何疑問,請告訴我:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM