0

I need a form field that if a number under 21 and over 35 is entered there is a pop up up that tells them to enter a number between 21 and 35.

Firstly I have seen this one, it doesn't solve my requirements:

Form validation with Javascript - Field value must be between 2 specific numbers

I have the following and it doesn't work, any idea why?

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["daysCalc"]["days"].value;
if (x>=21 && x<=35) {
    alert("Number must be between 21 and 35");
    return false;
}
}
</script>
</head>

<body>
<form name="daysCalc" action="" onsubmit="return validateForm()" method="post">
Days: <input type="text" name="days">
<input type="submit" value="Submit">
</form>
</body>

</html>

Your help would be appreciated.

Thanks in advance

2
  • 1
    Because your logic is exactly the wrong way around. You're showing the error message and return false when the number is between 21 and 35. Commented Nov 15, 2014 at 9:58
  • Can't believe I did that! Must be to early :| Thank you for spotting it! Commented Nov 15, 2014 at 10:11

2 Answers 2

1

You're actually sending the error message when the user is entering a number within the given range, not outside the given range.

Try this:

function validateForm() {
    var x = document.forms["daysCalc"]["days"].value;
    if (x < 21 || x > 35) {
        alert("Number must be between 21 and 35");
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function validateForm() {
    var x = document.forms["daysCalc"]["days"].value;
    if (x<=20 || x>=36) {
        alert("Number must be between 21 and 35");
        return false;

}
}
</script>
</head>

<body>
<form name="daysCalc" action="" onsubmit="return validateForm()" method="post">
Days: <input type="text" name="days">
<input type="submit" value="Submit">
</form>
</body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.