HTML Form Validation With JavaScript

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code


The form validation function, validate_form(), is embedded in the head element near the top of the page. The line (<script type="text/javascript">) tells the browser that we are writing some JavaScript, and the HTML comment (<!--) in the second line hides the script from older browsers that don’t understand JavaScript.

We use this ‘valid' variable to keep track of whether our form has been filled out correctly. If one of our checks fails, we’ll set valid to false. Next, we return the value of our 'valid' variable to the onSubmit event handler. If the value is true then the form will be sent to the server; if it’s false then the form will not be sent.

View the Output and Test the validation:

Save the source code provided in this post as HTML file. Open that file into browser. Keep all or any of the field empty/unselected and submit the form clicking the ‘Send Details’ button. You will be shown popup window with appropriate error message. If you fill all fields then no popup window will be displayed since all validations are ok.  To submit this page to the server you need to put your server-side page/program name in ‘action’ attribute of ‘<form>’ tag.