Validating form data

In this tutorial, you will learn how to use JavaScript to validate form data. Form validation ensures that the correct form data has been provided by the user. For example, we can check if an email address contains the @ symbol, if a post code is a 4-digit number, if a date of birth is within a specified range, and that a username does not contain illegal characters such as a dollar sign or percent symbol.

In the example below, form validation is used to check that a username and password that is submitted is not empty (the user must enter something for both the username and password). It will not actually check if the username and password is correct though (that requires some server-side processing and a database – if we want to have a secure form).

Watch the video below and then scroll down to see the code.

Here is the code for the HTML file which contains the form and JavaScript form validation:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Form Validation</title>
 <script type="text/javascript">
 
 // Form validation is used to ensure that correct form data is provided by the user
 // This example uses the code from the previous tutorial.
 // Remember, there is no PHP/server-side file to use the form data yet.
 // This file uses the onsubmit event to run the checkInfo() function which will validate form data.
 
 function checkInfo(){
 var username = document.getElementById('username').value;
 var password = document.getElementById('password').value;
 
 // this checks if username or password is an empty string
 if(username=="" || password==""){
 alert('Please complete all fields');
 return false;
 // return false will stop the form from sending data
 }
 else{
 return true;
 // return true will allow the form data to be sent
 }
 
 }
 
 </script>
 
</head>
<body>
 
<form action="submission.html" method="post" onsubmit="return checkInfo();">
 Username: <input type="text" name="username" id="username"/>
 Password: <input type="password" name="password" id="password"/>
 <input type="submit" value="Login"/>
</form>
 
</body>
</html>

Here is the code for the submission.html  page (‘thank you’ page) the user sees after the form has been submitted:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Form data submitted</title>
 <script type="text/javascript">
 
 // This file is used after the form has been submitted for the Form Submission tutorials.
 // Do not delete this file
 
 </script>
 
</head>
<body>
 
<p>Thank you for submitting your data</p>
 
</body>
</html>

Next tutorial: Radio buttons and form validation