PHP를 사용하여이 임의의 숫자를 추측하는 게임을 만들었으며 자바 스크립트를 사용하여 클라이언트 측 폼 유효성 검사를 구현하려고합니다. 스크립트는 1-100 사이의 숫자 만 허용하고 공백, 영숫자, 음수 및 부동 소수점 숫자 및/또는 이들을 혼합 한 것을 모두 거부해야합니다. 여기에 지금까지있어 스크립트의 :JavaScript 정규식 유효성 검사 실패
<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 random number game
고마워요!
1의 숫자를 확인하려면 보자 : 1과 100 사이 당신이 정규식을 사용하고 있기 때문에 정말 문자열)이며, 여기에 한 가지 방법입니다 -100 당신은 정규식이 필요하지 않습니다. – elclanrs