In this lesson, you'll learn how to validate a form using JavaScript. Form validation ensures that users enter correct data before submitting, like checking if an email is valid or a password is strong. This makes web applications more reliable and user-friendly.
You'll set up a new workspace in VS Code, create a simple registration form in HTML, style it with CSS, and add JavaScript to validate the name, email, and password fields. Finally, you'll test it and tackle a challenge to add an age field with validation.
First, create a new workspace for this lesson in VS Code.
Open VS Code and follow these steps:
File
' > 'Open Folder
'.FormValidation
' in your Documents folder.Now, create the basic HTML structure with a form.
In VS Code, with your project folder open:
New File
'.index.html
'.Add the following complete HTML code to 'index.html
':
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Demo</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>Registration Form</h1>
<form id="registrationForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<span id="nameError" class="error"></span><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<span id="emailError" class="error"></span><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<span id="passwordError" class="error"></span><br><br>
<button type="submit">Submit</button>
</form>
<script src="js/script.js"></script>
</body>
</html>
form
tag and inside that we have added 3 form elements; Name
, Email
and Password
fields.label
, input
and span
tags. Save the file (Ctrl+S
or Cmd+S
). This sets up a form with fields for name, email, and password, plus error spans. To view it, double-click 'index.html
' in your file explorer to open it in a web browser.
To style your form, create a CSS folder and file.
In VS Code:
New Folder
'.css
'.New File
'.styles.css
'.Add the following complete CSS code to 'styles.css
':
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
}
h1 {
color: navy;
}
form {
max-width: 400px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 10px;
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.error {
color: red;
display: block;
font-size: 0.8em;
margin-bottom: 10px;
}
Next, create a folder for JavaScript and add a script file.
In VS Code:
New Folder
'.js
'.js
' folder and select 'New File
'.script.js
'.For now, leave 'script.js
' empty.