I am trying to validate the form input but my validation is not working.
The string must have at least one letter or digit,
an integer should be between 0-11 and should pick at least one fruit.
But even if i dont enter any input,
it just go to the input_ok.html file.
It needs to pop-up the error window.
Here is my code:
function validateInput() {
var str = myForm.inputString.value;
var nbrStr = myForm.inputInteger.value;
var nbr = parseInt(nbrStr);
var fruit = myForm.fruit.value;
if (str != "" && nbrStr != "" && fruit != "" && !isNaN(nbr) && nbr < 11) {
return true;
} else {
var msg = "";
var strError = false;
if (str == "") {
msg += "\nPlease enter a string with at least one letter or digit";
strError = true;
}
if (nbrStr == "") {
msg += "\nPlease enter an integer in the range 0-11";
} else if (isNaN(nbr)) {
msg += "\nPlease enter an integer";
} else if (nbr > 11) {
msg += "\nPlease enter an integer less than 11";
}
if (strError) {
myForm.inputString.focus();
} else {
myForm.inputInteger.focus();
}
alert(msg);
}
return false;
}
<body>
<h1>Week 08, Exercise 01</h1>
<form action="week08_01servlet"
method="post"
name="myForm"
onsubmit="return validateInput();">
<p>Please enter the following information,
and then click the submit button.</p>
<p class="indent">A string with at least one letter or digit
<input type="text" name="inputString">
<br>An integer in the range 0-11
<input type="text" name="inputInteger">
<br>Pick a fruit <select name="fruit">
<option value="---">---
<option value="apple">apple
<option value="banana">banana
<option value="cherry">cherry
<option value="pear">pear
</select></p>
<p><input type="submit" value="Submit"></p>
<input type="hidden" name="command" value="do_it">
</form>
</body>
This is clearly homework, but I beleave every question deservers an answer. Valid xhtml5, javascript checked with jslint and compressed with ajaxmin. Enjoy.
Also, you might want to read ppks Introduction to Forms.