Form Field Validation with JavaScript

Enter First Name:

Enter Zip Code (99999-9999):

See if you can find the new validation section. Hint: It starts with an IF statement.

The Source

<html>
<head>
<SCRIPT type="text/javascript">
  function validfn(fnm)
  {
    fnlen=fnm.length
    if (fnlen == 0)
     {alert("First name is required")
      document.dataentry.fn.focus()}
  }
  function validZip(zip)
  {
      len=zip.length
      digits="0123456789"
      if(len != 5 && len != 10)
         {alert("Zip is not the correct length")
          document.dataentry.zip.focus()}

      for(i=0; i<5; i++)
        {if (digits.indexOf(zip.charAt(i))<0)
           {alert("First five digits must be numeric")
            document.dataentry.zip.focus()
            break}
        }

      if(len>5 && zip.charAt(5) != "-")
          {alert("Sixth character must be a '-'")
           document.dataentry.zip.focus()}
  }
</script>
</head>
<body>
<form name="dataentry">
    <h2>Form Field Validation with JavaScript</h2>
     Enter First Name:<br>
     <input type="text" 
	 	name="fn" 
		onBlur="validfn(fn.value)">
     <SCRIPT type="text/javascript">
        document.dataentry.fn.focus()
      </script>
     <p>
     Enter Zip Code (99999-9999):<br>
    <input type="text" name="zip" size=10 >
    <p>
    <input type="button"  
		value="Submit" 
		onClick="validZip(zip.value)">
</body>
</html>

Close this window to return to Primer #29