Web Technology I · Unit 8
JavaScript Events and Form Validation
Exam-focused notes for JavaScript Events and Form Validation (Web Technology I, BIT251): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.
JavaScript Events and Form Validation in short
Events let JavaScript react when a user clicks, types or submits a form. Form validation uses events to check input before it reaches the server. This chapter covers both.
What this unit covers
- HTML events and event handlers
- Onclick and onkeypress events
- Form validation concept and purpose
- Email validation patterns
- Password length validation
- Checkbox validation
- Required field validation
- Pattern matching validation
HTML events and event handlers
2081 · 10 marks
Describe HTML events.Write HTML script to demonstrate Onkeypress and Onclick events.[6+4]
Form validation concept and purpose
2081 · 5 marks
Create a web form and write JavaScript to show form validation. The validation should be done for required, length and some pattern in the HTML form elements. [5]
2080 · 10 marks
Create an HTML form for signup. The form should contain form elements for username, password, email, country, gender, and hobbies. The username should be at least of 8 length, password should be of 6 length having at least one digit. The username and password should be present. The email should be valid. The country field in dropdown should be selected. The gender and hobbies in radio and checkboxes should also be checked respectively. Now write JavaScript function to validate the form as per mentioned.[10]
Show solved answerHide answer
HTML Form with JavaScript Validation
Complete Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup Form</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 500px;
margin: 40px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
}
h2 {
text-align: center;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"],
input[type="password"],
input[type="email"],
select {
width: 100%;
padding: 8px;
box-sizing: border-box;
border: 1px solid #aaa;
border-radius: 4px;
}
.error {
color: red;
font-size: 13px;
margin-top: 4px;
}
input[type="submit"] {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h2>Signup Form</h2>
<form name="signupForm" onsubmit="return validateForm()">
<!-- Username -->
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter username">
<span class="error" id="usernameError"></span>
</div>
<!-- Password -->
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password">
<span class="error" id="passwordError"></span>
</div>
<!-- Email -->
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter email">
<span class="error" id="emailError"></span>
</div>
<!-- Country -->
<div class="form-group">
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">-- Select Country --</option>
<option value="nepal">Nepal</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
<option value="australia">Australia</option>
</select>
<span class="error" id="countryError"></span>
</div>
<!-- Gender -->
<div class="form-group">
<label>Gender:</label>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
<span class="error" id="genderError"></span>
</div>
<!-- Hobbies -->
<div class="form-group">
<label>Hobbies:</label>
<input type="checkbox" name="hobbies" value="reading"> Reading
<input type="checkbox" name="hobbies" value="gaming"> Gaming
<input type="checkbox" name="hobbies" value="travelling"> Travelling
<input type="checkbox" name="hobbies" value="cooking"> Cooking
<span class="error" id="hobbiesError"></span>
</div>
<!-- Submit -->
<div class="form-group">
<input type="submit" value="Sign Up">
</div>
</form>
<script>
function validateForm() {
// Clear all previous error messages
var errorIds = [
"usernameError", "passwordError", "emailError",
"countryError", "genderError", "hobbiesError"
];
for (var i = 0; i < errorIds.length; i++) {
document.getElementById(errorIds[i]).innerText = "";
}
var isValid = true;
// ---- 1. Username Validation ----
var username = document.getElementById("username").value.trim();
if (username === "") {
document.getElementById("usernameError").innerText
= "Username is required.";
isValid = false;
} else if (username.length < 8) {
document.getElementById("usernameError").innerText
= "Username must be at least 8 characters long.";
isValid = false;
}
// ---- 2. Password Validation ----
var password = document.getElementById("password").value.trim();
var hasDigit = /\d/; // Regular expression to check for at least one digit
if (password === "") {
document.getElementById("passwordError").innerText
= "Password is required.";
isValid = false;
} else if (password.length < 6) {
document.getElementById("passwordError").innerText
= "Password must be at least 6 characters long.";
isValid = false;
} else if (!hasDigit.test(password)) {
document.getElementById("passwordError").innerText
= "Password must contain at least one digit.";
isValid = false;
}
// ---- 3. Email Validation ----
var email = document.getElementById("email").value.trim();
var emailPattern = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (email === "") {
document.getElementById("emailError").innerText
= "Email is required.";
isValid = false;
} else if (!emailPattern.test(email)) {
document.getElementById("emailError").innerText
= "Please enter a valid email address.";
isValid = false;
}
// ---- 4. Country Validation (dropdown) ----
var country = document.getElementById("country").value;
if (country === "") {
document.getElementById("countryError").innerText
= "Please select a country.";
isValid = false;
}
// ---- 5. Gender Validation (radio buttons) ----
var genders = document.getElementsByName("gender");
var genderChosen = false;
for (var g = 0; g < genders.length; g++) {
if (genders[g].checked) {
genderChosen = true;
break;
}
}
if (!genderChosen) {
document.getElementById("genderError").innerText
= "Please select your gender.";
isValid = false;
}
// ---- 6. Hobbies Validation (checkboxes) ----
var hobbies = document.getElementsByName("hobbies");
var hobbyCount = 0;
for (var h = 0; h < hobbies.length; h++) {
if (hobbies[h].checked) {
hobbyCount++;
}
}
if (hobbyCount === 0) {
document.getElementById("hobbiesError").innerText
= "Please select at least one hobby.";
isValid = false;
}
// ---- Final result ----
if (isValid) {
alert("Signup successful.");
}
// false prevents submission, true allows it
return isValid;
}
</script>
</body>
</html>
How Each Element is Validated
| Element | Type | How the value is read | Rule |
|---|---|---|---|
| Username | Text box | getElementById("username").value | Required, at least 8 characters |
| Password | Password box | getElementById("password").value | Required, at least 6 characters, must contain a digit |
| Email box | getElementById("email").value | Required, must match the email pattern | |
| Country | Dropdown | getElementById("country").value | Must not be the empty placeholder option |
| Gender | Radio group | getElementsByName("gender") | Exactly one button must be checked |
| Hobbies | Checkbox group | getElementsByName("hobbies") | At least one box must be checked |
Radio buttons and checkboxes share a name rather than an id, which is why they are read with getElementsByName() and scanned in a loop, while single-valued controls are read directly by id.
Conclusion
The function clears the old messages first, then tests every control and records failures in a single isValid flag instead of returning early, so the user sees all the problems in one pass. Returning false from onsubmit cancels the submission. This client-side check gives instant feedback, but the same rules must be repeated on the server because JavaScript can be disabled or bypassed.
2079 · 5 marks
What is form validation? Write a JavaScript function to validate an email field, password having length at least 6 and a collection of checkbox of 3 hobbies having at least one of them to be checked. [5]
2080.2 · 10 marks
What is client side validation? Why form validation is needed? Write a JavaScript program to validate a form that contains text field, password field, radio button field, checkbox and dropdown select field. Write validation for each field as required field. Also add validation constraints for password[10]
Show solved answerHide answer
Client-Side Validation and Form Validation in JavaScript
What is Client-Side Validation?
Client-side validation is the process of validating user input data in the browser (on the client side) before the data is submitted to the server. It is implemented using scripting languages like JavaScript and runs on the user's machine without requiring a round trip to the server.
In client-side validation, the browser checks the form fields for correctness (e.g., required fields, format, length) and provides immediate feedback to the user if something is wrong.
Why is Form Validation Needed?
Form validation is needed for the following reasons:
| Reason | Explanation |
|---|---|
| Data Integrity | Ensures only correct and complete data is submitted |
| User Experience | Provides instant feedback without page reload |
| Reduce Server Load | Invalid requests are stopped before reaching the server |
| Security | Prevents empty or malformed data from being processed |
| Business Rules | Enforces constraints like password length, required fields |
| Prevent Errors | Avoids database errors caused by wrong data types or empty values |
JavaScript Form Validation Program
The form contains:
- Text field (Name)
- Password field (with constraints)
- Radio button (Gender)
- Checkbox (Terms & Conditions)
- Dropdown select (Country)
Password Validation Constraints:
- Must not be empty
- Minimum 8 characters long
- Must contain at least one uppercase letter
- Must contain at least one lowercase letter
- Must contain at least one digit
- Must contain at least one special character
HTML + JavaScript Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f2f2f2;
}
form {
background-color: white;
padding: 30px;
width: 420px;
border-radius: 8px;
box-shadow: 0 0 10px #ccc;
}
h2 {
text-align: center;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"],
input[type="password"],
select {
width: 100%;
padding: 8px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}
.error {
color: red;
font-size: 13px;
margin-top: 4px;
}
.success {
color: green;
font-size: 13px;
margin-top: 4px;
}
input[type="submit"] {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form name="registrationForm" onsubmit="return validateForm()">
<h2>Registration Form</h2>
<!-- Text Field: Name -->
<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name">
<span id="nameError" class="error"></span>
</div>
<!-- Password Field -->
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password">
<span id="passwordError" class="error"></span>
</div>
<!-- Radio Button: Gender -->
<div class="form-group">
<label>Gender:</label>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
<span id="genderError" class="error"></span>
</div>
<!-- Checkbox: Terms and Conditions -->
<div class="form-group">
<label>
<input type="checkbox" id="terms" name="terms">
I agree to the Terms and Conditions
</label>
<span id="termsError" class="error"></span>
</div>
<!-- Dropdown Select: Country -->
<div class="form-group">
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">-- Select Country --</option>
<option value="nepal">Nepal</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
<span id="countryError" class="error"></span>
</div>
<!-- Submit Button -->
<div class="form-group">
<input type="submit" value="Register">
</div>
<span id="successMsg" class="success"></span>
</form>
<script>
function validateForm() {
// Clear all previous error messages
document.getElementById("nameError").textContent = "";
document.getElementById("passwordError").textContent = "";
document.getElementById("genderError").textContent = "";
document.getElementById("termsError").textContent = "";
document.getElementById("countryError").textContent = "";
document.getElementById("successMsg").textContent = "";
var isValid = true;
// ---- 1. Text field: Name ----
var name = document.getElementById("name").value.trim();
if (name === "") {
document.getElementById("nameError").textContent = "Name is required.";
isValid = false;
}
// ---- 2. Password field ----
var password = document.getElementById("password").value;
var pwdPattern =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$/;
if (password === "") {
document.getElementById("passwordError").textContent =
"Password is required.";
isValid = false;
} else if (!pwdPattern.test(password)) {
document.getElementById("passwordError").textContent =
"Password must be at least 8 characters and include an uppercase letter, " +
"a lowercase letter, a digit and a special character.";
isValid = false;
}
// ---- 3. Radio button: Gender ----
var genders = document.getElementsByName("gender");
var genderChosen = false;
for (var i = 0; i < genders.length; i++) {
if (genders[i].checked) {
genderChosen = true;
break;
}
}
if (!genderChosen) {
document.getElementById("genderError").textContent =
"Please select your gender.";
isValid = false;
}
// ---- 4. Checkbox: Terms and Conditions ----
if (!document.getElementById("terms").checked) {
document.getElementById("termsError").textContent =
"You must agree to the Terms and Conditions.";
isValid = false;
}
// ---- 5. Dropdown: Country ----
if (document.getElementById("country").value === "") {
document.getElementById("countryError").textContent =
"Please select a country.";
isValid = false;
}
// ---- Result ----
if (isValid) {
document.getElementById("successMsg").textContent =
"Registration successful. All fields are valid.";
}
// Returning false cancels the submission
return isValid;
}
</script>
</body>
</html>
How Each Control is Checked
| Control | Read using | Rule |
|---|---|---|
| Text field (Name) | getElementById("name").value | Must not be empty |
| Password field | getElementById("password").value | The six constraints listed above |
| Radio button (Gender) | getElementsByName("gender") | Exactly one option must be checked |
| Checkbox (Terms) | getElementById("terms").checked | Must be ticked |
| Dropdown (Country) | getElementById("country").value | Must not be the placeholder option |
Conclusion
Client-side validation runs inside the browser before anything is sent, so the user is corrected immediately and the server is spared a pointless request. The program above shows the pattern for every kind of control: single-valued fields are read by id, grouped controls (radio buttons and checkboxes) are read by name and scanned, and the whole form reports through one isValid flag whose value is returned to onsubmit. It never replaces server-side validation, which remains the only trustworthy check.
0 · 10 marks
Create a HTML form with fields like username, password, email, country. The username should be textbox, password and email should be the password and email fields. The country should be drop down. Now write JavaScript function for form validation. Your function should validate the username to be of length 5, password should start with digit and should be alphanumeric. The email should be valid. The country field should be selected.[10]
Make Unit 8 stick
Practice BIT251 with flashcards & quizzes