Intermediate Web Publishing

JavaScript and Forms: data validation example

<FORM METHOD=POST
 ACTION="http://www.uoregon.edu/cgi-bin/post-query">
My favorite number: <INPUT TYPE=text NAME=best><BR>
<INPUT TYPE=submit>
</FORM>

Exercise: Step 1: create the HTML form above. Step 2: Add JavaScript code to the form that verifies that the user has typed a number in the "favorite number" box.

Sample solution:

<SCRIPT LANGUAGE="JavaScript"> <!--
function validate(data) {
  if (parseInt(data) != data) {
    alert(data + "Is not a positive number")
    return false
  } else { return true }
}
// --></SCRIPT>

Note: you must also modify the FORM tag to add an ONSUBMIT, e.g.:

<FORM ONSUBMIT="return validate(this.best.value)"
 ...


[up] nextData validation with regular expressions