Javascript DOM Form validate

Description

Javascript DOM Form validate

 P:In this example, you have a simple form consisting of two text boxes and a button. 

The top text box is for the users' name, and the second is for their age.

This example does not work properly on Firefox.

View in separate window


  <!DOCTYPE html> 

  <html lang="en"> 
  <body> 
      <form action="" name="form1"> 
          Please enter the following details: 
          <p> 
              Name: /*from   ww w. j a  va2  s  . c o  m*/
              <input type="text" name="txtName" /> 
          </p> 
          <p> 
              Age: 
              <input type="text" name="txtAge" size="3" maxlength="3" /> 
          </p> 
          <p> 
              <input type="button" value="Check details" name="btnCheckForm"> 
          </p> 
      </form> 

      <script> 
          let myForm = document.form1; 

          function btnCheckFormClick(e) { 
              let txtName = myForm.txtName; 
              let txtAge = myForm.txtAge; 

              if (txtAge.value == ""  || txtName.value == "") { 
                  console.log("Please complete all of the form"); 

                  if (txtName.value == "") { 
                      txtName.focus(); 
                } else { 
                    txtAge.focus(); 
                } 
            } else { 
                console.log("Thanks for completing the form " +  txtName.value); 
            } 
        } 

        function txtAgeBlur(e) { 
            let target = e.target; 

            if (isNaN(target.value)) { 
                console.log("Please enter a valid age"); 
                target.focus(); 
                target.select(); 
            } 
        } 

        function txtNameChange(e) { 
            console.log("Hi " + e.target.value); 
        } 

        myForm.txtName.addEventListener("change", txtNameChange); 
        myForm.txtAge.addEventListener("blur", txtAgeBlur); 
        myForm.btnCheckForm.addEventListener("click", btnCheckFormClick); 
    </script> 
</body> 
</html> 



PreviousNext

Related