0% found this document useful (0 votes)
56 views21 pages

A039 - Exp 8 - Form Validation

This document provides instructions for validating HTML forms using JavaScript. It discusses using JavaScript to validate form fields, including name, password, email, numbers, and dates. It provides code examples for validating that a name is entered, password is at least 6 characters, emails and phone numbers match the appropriate formats, and numbers only contain numeric values. Students are asked to create a form with JavaScript validations for various field types as discussed in class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views21 pages

A039 - Exp 8 - Form Validation

This document provides instructions for validating HTML forms using JavaScript. It discusses using JavaScript to validate form fields, including name, password, email, numbers, and dates. It provides code examples for validating that a name is entered, password is at least 6 characters, emails and phone numbers match the appropriate formats, and numbers only contain numeric values. Students are asked to create a form with JavaScript validations for various field types as discussed in class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

SVKM’s NMIMS

School of Technology Management & Engineering


Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
PART A
(Part A: TO BE REFFERED BY STUDENTS)
Experiment No. 08
A.1 AIM:
Validation of HTML forms using JavaScript

A.2 Pre requisite:


Basic Knowledge of HTML and JavaScript

A.3 Outcome:
After successful completion of this experiment students will be able to:

1. Apply appropriate validations on the HTML forms using JavaScript

A.4 Theory:
JavaScript is the programming language of the Web. All modern HTML pages are using
JavaScript.

JavaScript is one of 3 languages all web developers MUST learn:

1. HTML to define the content of web pages


2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a
server.

In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.

1. <script>
2. function validateform(){
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (name==null || name==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(password.length<6){
10. alert("Password must be at least 6 characters long.");
11. return false;
12. }
13. }
14. </script>

JavaScript Retype Password Validation

1. <script type="text/javascript">
2. function matchpass(){
3. var firstpassword=document.f1.password.value;
4. var secondpassword=document.f1.password2.value;
5.
6. if(firstpassword==secondpassword){
7. return true;
8. }
9. else{
10. alert("password must be same!");
11. return false;
12. }
13. }
14. </script>

JavaScript Number Validation


SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
1. <script>
2. function validate(){
3. var num=document.myform.num.value;
4. if (isNaN(num)){
5. document.getElementById("numloc").innerHTML="Enter Numeric value only";
6. return false;
7. }else{
8. return true;
9. }
10. }
11. </script>

JavaScript email validation

1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");
6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+
dotposition);
9. return false;
10. }
11. }
12. </script>

Form validation can also be done by using Regular expression

The following table illustrates the meaning of each part of the regular expression used
to validate the password:
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
Password RegEx Meaning

^ The password starts

(?=.*[a-z]) The password must contain at least one lowercase character

(?=.*[A-Z]) The password must contain at least one uppercase character

(?=.*[0-9]) The password must contain at least one number

(?=.*[!@#$%^&*]) The password must contain at least one special character.

(?=.{8,}) The password must be eight characters or longer

// Javascript reGex for Email Validation.

var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;

var regPhone=/^\d{10}$/; // Javascript reGex for Phone Number validation.


var regName = /\d+$/g; // Javascript reGex for Name validation

function GEEKFORGEEKS(){
var name =
document.forms.RegForm.Name.value;
var email =
document.forms.RegForm.EMail.value;
var phone =
document.forms.RegForm.Telephone.value;
var what =
document.forms.RegForm.Subject.value;
var password =
document.forms.RegForm.Password.value;
var address =
document.forms.RegForm.Address.value;
//Javascript reGex for Email Validation.
var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
// Javascript reGex for Phone Number validation.
var regPhone=/^\d{10}$/;
// Javascript reGex for Name validation
var regName = /\d+$/g;

if (name == "" || regName.test(name)) {


window.alert("Please enter your name properly.");
name.focus();
return false;
}

if (address == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}

if (email == "" || !regEmail.test(email)) {


window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (password == "") {
alert("Please enter your password");
password.focus();
return false;
}

if(password.length <6){
alert("Password should be atleast 6 character long");
password.focus();
return false;

}
if (phone == "" || !regPhone.test(phone)) {
alert("Please enter valid phone number.");
phone.focus();
return false;
}

if (what.selectedIndex == -1) {
alert("Please enter your course.");
what.focus();
return false;
}
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
return true;
} {
var name =
document.forms.RegForm.Name.value;
var email =
document.forms.RegForm.EMail.value;
var phone =
document.forms.RegForm.Telephone.value;
var what =
document.forms.RegForm.Subject.value;
var password =
document.forms.RegForm.Password.value;
var address =
document.forms.RegForm.Address.value;
//Javascript reGex for Email Validation.
var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
// Javascript reGex for Phone Number validation.
var regPhone=/^\d{10}$/;
// Javascript reGex for Name validation
var regName = /\d+$/g;

if (name == "" || regName.test(name)) {


window.alert("Please enter your name properly.");
name.focus();
return false;
}

if (address == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}

if (email == "" || !regEmail.test(email)) {


window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (password == "") {
alert("Please enter your password");
password.focus();
return false;
}

if(password.length <6){
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
alert("Password should be atleast 6 character long");
password.focus();
return false;

}
if (phone == "" || !regPhone.test(phone)) {
alert("Please enter valid phone number.");
phone.focus();
return false;
}

if (what.selectedIndex == -1) {
alert("Please enter your course.");
what.focus();
return false;
}

return true;
}

A.5 Procedure/Task:
1. Create a form or use the form created in the earlier experiment.
2. Insert the JavaScript validations in those forms as discussed and practiced in class (All
characters in a field validation, All Numbers in a field validation, Phone number validation, Password validation,
Email id validation, Date format validation etc.)

3. Prepare the document. Save and close the file and name it as EXP08_Name of Student
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
PART B

(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the practical. The
soft copy must be uploaded on the Blackboard or emailed to the concerned lab in charge faculties
at the end of the practical in case the there is no Black board access available)

Roll No. : A039 Name: Masrita.Mangalarapu


Class : MCA SEM 1 Batch :
Date of Experiment :16-09-23 Date/Time of Submission : 16-09-23
Grade :

B.1 Code:

(Paste your Code here)

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
body {

font-family: Arial, sans-serif;

background-color: #e8d1f0;

margin: 0;

padding: 0;

h1 {

text-align: center;
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual

color: #333;

form {

max-width: 400px;

margin: 0 auto;

padding: 20px;

background-color: #fff;

border: 1px solid #ccc;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

label {

font-weight: bold;

input[type="text"] {

width: 100%;

padding: 10px;

margin-bottom: 10px;
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

}
input[type="email"] {

width: 100%;

padding: 10px;

margin-bottom: 10px;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

}
input[type="date"] {

width: 100%;

padding: 10px;

margin-bottom: 10px;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

}
input[type="tel"] {

width: 100%;
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
padding: 10px;

margin-bottom: 10px;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

input[type="checkbox"] {

margin-right: 5px;

input[type="submit"] {

background-color: #333;

color: #fff;

padding: 10px 20px;

border: none;

border-radius: 4px;

cursor: pointer;

input[type="submit"]:hover {
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual

background-color: #555;

.error {

color: red;

}
.error-message1 {
color: red;
display: none;
}

</style>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<h1 style= "text-align:center;">SVKM's NMIMS</h1>
<h2 style= "text-align:center;">Mukesh Patel School of Technology Manganement
& Engineering</h2>
<h4 style= "text-align:center;"> (Mumbai Campus) A.Y 2023-24</h4>
<br>
<h2 style="text-align: center;">Student Registration </h2><br>
<form action="Education_details.html" style="text-align: center;" >

<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<div id="nameError" class="error-message"></div>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<div id="emailError" class="error-message"></div>

<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>
<div id="phoneError" class="error-message"></div><br>
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate" required>
<div id="birthdateError" class="error-message"></div>
<label>Checkboxes (Select at least 2):</label><br><br>

<label>
<input type="checkbox" id="checkbox1" name="checkbox1"> Checkbox 1
</label>
<br>
<label>
<input type="checkbox" id="checkbox2" name="checkbox2"> Checkbox 2
</label>
<br>
<label>
<input type="checkbox" id="checkbox3" name="checkbox3"> Checkbox 3
</label>
<br>
<div class="error-message1" id="checkboxError">Please select at least
two checkboxes.</div>
<br>

<input type="submit" value="Submit">


</form>

<script>
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const phone = document.getElementById('phone').value;
const birthdate = new
Date(document.getElementById('birthdate').value);
const checkboxes =
document.querySelectorAll('input[type="checkbox"]');
let checkedCount = 0;
const currentDate = new Date();

const nameError = document.getElementById('nameError');


const emailError = document.getElementById('emailError');
const phoneError = document.getElementById('phoneError');
const birthdateError = document.getElementById('birthdateError');
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
// Reset error messages
nameError.textContent = '';
emailError.textContent = '';
phoneError.textContent = '';
birthdateError.textContent = '';

// Validate name (only characters, no numbers)


if (!/^[a-zA-Z\s]*$/.test(name)) {

alert("Name should contain only characters and spaces.")


return false;
}

// Validate email
if (!/^\S+@\S+\.\S+$/.test(email)) {
emailError.textContent = 'Invalid email address.';
return false;
}

// Validate phone number (10 digits)


if (!/^\d{10}$/.test(phone)) {
phoneError.textContent = 'Phone number should be 10 digits.';
return false;
}

// Calculate age
const age = currentDate.getFullYear() - birthdate.getFullYear();

// Check if age is less than 18


if (age < 18) {
birthdateError.textContent = 'You must be at least 18 years
old.';
return false;
}

checkboxes.forEach(checkbox => {
if (checkbox.checked) {
checkedCount++;
}
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
});

if (checkedCount < 2) {
document.getElementById('checkboxError').style.display =
'block';
return false;
}

return true;
}

</script>
</body>
</html>

B.2 Output

(Take screen shots of the output at run time and paste it here)
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual

B.3 Conclusion:

(Students must write the conclusion as per the attainment of individual outcome listed above)

In conclusion, JavaScript form validation is a crucial front-end technique that enhances user experience
by ensuring that data submitted through web forms is accurate, complete, and secure. Through the use
of conditional statements, regular expressions, and event handlers, JavaScript enables developers to
create responsive and error-free forms. This process helps prevent users from submitting invalid or
malicious data, reducing the risk of data breaches and enhancing the overall functionality and reliability
of web applications. Effective form validation is an essential component of web development that
contributes to user satisfaction and data integrity.

B.3 Observations and Learning:

(Students must write their observations and learnings as per the attainment of individual outcome listed
above)

Observations:
1. Enhances user experience with immediate feedback.
2. Maintains data integrity and accuracy.
3. Mitigates security risks by preventing malicious input.
4. Requires cross-browser compatibility considerations.
5. Relies on event handlers for validation triggers.
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
Learnings:
1. Master various validation techniques.
2. Create clear error messages for user guidance.
3. Implement server-side validation for resilience.
4. Test rigorously across browsers and devices.
5. Prioritize security with input sanitization.
6. Document validation rules and procedures.

B.4 Question of Curiosity

(To be answered by student based on the practical performed and learning/observations)

Q1. Why are validations necessary in HTML forms? Explain with suitable reason.
 Data Accuracy: Validations ensure that the data submitted through a form is accurate
and meets the expected criteria. This prevents users from accidentally or intentionally
entering incorrect or invalid information, which could lead to errors or inaccuracies in the
system.
 User Experience: Proper validation provides immediate feedback to users, helping them
understand and correct any errors they've made in filling out the form. This improves the
overall user experience by reducing frustration and the likelihood of form submission
failures.
 Data Integrity: Validations help maintain data integrity within the application or
database. Without validation, incorrect or maliciously crafted data could be submitted,
potentially compromising the functionality and security of the system.

Q2. List down the different validators that can be used in an HTML form? Explain any three of
them with script syntax and example.
1. Username
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<input type="submit" value="Submit">
</form>
2. Pattern Validator (Email):
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-
9.-]+\.[a-zA-Z]{2,}" required>
<input type="submit" value="Submit">
</form>
3. Number Validator:
<form>
SVKM’s NMIMS
School of Technology Management & Engineering
Computer Engineering Department (MCA Sem I/III)
Web Technology
Lab Manual
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<input type="submit" value="Submit">
</form>

You might also like