A039 - Exp 8 - Form Validation
A039 - Exp 8 - Form Validation
A.3 Outcome:
After successful completion of this experiment students will be able to:
A.4 Theory:
JavaScript is the programming language of the Web. All modern HTML pages are using
JavaScript.
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>
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>
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>
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
var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
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 (address == "") {
window.alert("Please enter your address.");
address.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 (address == "") {
window.alert("Please enter your address.");
address.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
(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)
B.1 Code:
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 {
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;
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-radius: 4px;
box-sizing: border-box;
}
input[type="date"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
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-radius: 4px;
box-sizing: border-box;
input[type="checkbox"] {
margin-right: 5px;
input[type="submit"] {
background-color: #333;
color: #fff;
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>
<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();
// Validate email
if (!/^\S+@\S+\.\S+$/.test(email)) {
emailError.textContent = 'Invalid email address.';
return false;
}
// Calculate age
const age = currentDate.getFullYear() - birthdate.getFullYear();
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.
(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.
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>