andy
andy

Reputation: 459

Javascript Form Validation Between 2 Numbers

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

Upvotes: 0

Views: 5275

Answers (2)

Hussy Borad
Hussy Borad

Reputation: 583

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

Upvotes: 0

Kristoffer Svanmark
Kristoffer Svanmark

Reputation: 778

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

Upvotes: 1

Related Questions