Textbox HTML Forms with Validation

Is current?: 
Yes

The textbox-validate template textbox-validate.htm is a type of HTML form that is a variant of the textbox.  The validation functionality uses Javascript code to present an alert to users who have typed in invalid input.  Two examples are provided: email address validation and number validation. These validations are sticky in this template.  That is, the form will not be submitted until and unless the user provides valid data for both items.

The use of the fake button and the distinction between the fake button and real button is explained in the dropdown-nag entry. The onclick event handler in the fake button on line 61 is the function dovalidate().  When the user clicks on the Continue button, dovalidate() checks if the user has provided valid input.  If the input is invalid then the user is alerted; else the form is submitted using document.form1.submit().  The dovalidate()for textbox is below:

<script type="text/javascript">

  function dovalidate() {

    var allanswered=true;

    if (!validateEmail(document.form1.tbitem1.value)) allanswered=false;// check if valid email
    if (!isNumber(document.form1.tbitem2.value)) allanswered=false;// check if valid number

    if (!allanswered)
        alert("Please type your email correctly and provide a valid number for the time spent.");

         else document.form1.submit();

  }
</script>

It is possible to modify this to check for numbers in particular ranges using additional code. If the number if valid, one can convert the variable value to a number and check if it in a particular range (here 18 to 95) and alert the user if it is outside the range as follows:

<script type="text/javascript">

  function dovalidate() {

    var allanswered=true;

    if (!validateEmail(document.form1.tbitem1.value)) allanswered=false;// check if valid email
    if (!isNumber(document.form1.tbitem2.value)) {
          allanswered=false;
          var mynumber = parseFloat(document.form1.tbitem2.value);
          if ((mynumber<18) || (mynumber>95))alert("Value outside range 18 – 95. Try again.");
         }
    if (!allanswered)
        alert("Please type your email correctly and provide a valid number for the time spent.");

         else document.form1.submit();

  }
</script>