0% found this document useful (0 votes)
2 views

Java Validation program (1)

The document contains multiple HTML forms demonstrating JavaScript validation techniques for user input, including alert messages for errors and displaying results upon successful submission. It features various validation methods, such as checking required fields, using regular expressions for email and mobile number formats, and collecting selected hobbies. Additionally, it includes a grocery list example that calculates the total cost of selected items using checkboxes.

Uploaded by

2212077sankar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Validation program (1)

The document contains multiple HTML forms demonstrating JavaScript validation techniques for user input, including alert messages for errors and displaying results upon successful submission. It features various validation methods, such as checking required fields, using regular expressions for email and mobile number formats, and collecting selected hobbies. Additionally, it includes a grocery list example that calculates the total cost of selected items using checkboxes.

Uploaded by

2212077sankar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Java Validation program with alert message

<!DOCTYPE html>

<html>

<head>

<title>Form Validation Example</title>

<style>

.output { margin-top: 20px; }

</style>

</head>

<body>

<h2>Form Validation Example</h2>

<form id="myForm">

<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br><br>

<label for="gender">Gender:</label><br>

<input type="radio" id="male" name="gender" value="Male">

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="Female">

<label for="female">Female</label><br><br>

<label for="hobbies">Hobbies:</label><br>

<input type="checkbox" id="reading" name="hobbies" value="Reading">

<label for="reading">Reading</label>

<input type="checkbox" id="sports" name="hobbies" value="Sports">

<label for="sports">Sports</label><br><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br><br>


<label for="mobile">Mobile Number:</label><br>

<input type="text" id="mobile" name="mobile" required><br><br>

<label for="comments">Comments:</label><br>

<textarea id="comments" name="comments" rows="4" cols="50"></textarea><br><br>

<label for="dob">Date of Birth:</label><br>

<input type="date" id="dob" name="dob" required><br><br>

<button type="button" onclick="validateForm()">Submit</button>

</form>

<div id="output" class="output"></div>

<script>

function validateForm() {

// Get form values

const name = document.getElementById("name").value;

const gender = document.querySelector('input[name="gender"]:checked');

const hobbyCheckboxes = document.querySelectorAll('input[name="hobbies"]:checked');

const email = document.getElementById("email").value;

const mobile = document.getElementById("mobile").value;

const comments = document.getElementById("comments").value;

const dob = document.getElementById("dob").value;

// Regular Expressions

const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

const mobilePattern = /^[0-9]{10}$/; // Assumes 10-digit mobile number without country code

// Validate the form


if (!name) {

alert("Name is required.");

return;

if (!gender) {

alert("Gender is required.");

return;

// Manually collect selected hobbies

const hobbies = [];

for (let checkbox of hobbyCheckboxes) {

hobbies.push(checkbox.value);

if (hobbies.length === 0) {

alert("Please select at least one hobby.");

return;

if (!email || !emailPattern.test(email)) {

alert("Please enter a valid email address.");

return;

if (!mobile || !mobilePattern.test(mobile)) {

alert("Please enter a valid mobile number (10 digits).");

return;

if (!dob) {

alert("Date of birth is required.");

return;

}
// Display the results

const output = document.getElementById("output");

output.innerHTML = `<h3>Form Submitted Successfully!</h3>

<p><strong>Name:</strong> ${name}</p>

<p><strong>Gender:</strong> ${gender.value}</p>

<p><strong>Hobbies:</strong> ${hobbies.join(', ')}</p>

<p><strong>Email:</strong> ${email}</p>

<p><strong>Mobile Number:</strong> ${mobile}</p>

<p><strong>Comments:</strong> ${comments}</p>

<p><strong>Date of Birth:</strong> ${dob}</p>`;

</script>

</body>

</html>

Java Validation program with error nearby


<!DOCTYPE html>

<html>

<head>

<title>Form Validation Example</title>

<style>

.output { margin-top: 20px; }

.error { color: red; font-size: 0.9em; }

</style>

</head>

<body>

<h2>Form Validation Example</h2>

<form id="myForm">
<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br>

<span id="nameError" class="error"></span><br><br>

<label for="gender">Gender:</label><br>

<input type="radio" id="male" name="gender" value="Male">

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="Female">

<label for="female">Female</label><br>

<span id="genderError" class="error"></span><br><br>

<label for="hobbies">Hobbies:</label><br>

<input type="checkbox" id="reading" name="hobbies" value="Reading">

<label for="reading">Reading</label>

<input type="checkbox" id="sports" name="hobbies" value="Sports">

<label for="sports">Sports</label><br>

<span id="hobbiesError" class="error"></span><br><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br>

<span id="emailError" class="error"></span><br><br>

<label for="mobile">Mobile Number:</label><br>

<input type="text" id="mobile" name="mobile" required><br>

<span id="mobileError" class="error"></span><br><br>

<label for="comments">Comments:</label><br>

<textarea id="comments" name="comments" rows="4" cols="50"></textarea><br><br>

<label for="dob">Date of Birth:</label><br>

<input type="date" id="dob" name="dob" required><br><br>


<span id="dobError" class="error"></span><br><br>

<button type="button" onclick="validateForm()">Submit</button>

</form>

<div id="output" class="output"></div>

<script>

function validateForm() {

// Clear previous errors

document.querySelectorAll('.error').forEach(function(errorSpan) {

errorSpan.textContent = '';

});

let errorMessages = false;

// Get form values

const name = document.getElementById("name").value;

const gender = document.querySelector('input[name="gender"]:checked');

const hobbies = [];

const hobbyCheckboxes = document.querySelectorAll('input[name="hobbies"]:checked');

// Collect selected hobbies using a for loop

for (let i = 0; i < hobbyCheckboxes.length; i++) {

hobbies.push(hobbyCheckboxes[i].value);

const email = document.getElementById("email").value;

const mobile = document.getElementById("mobile").value;

const comments = document.getElementById("comments").value;

const dob = document.getElementById("dob").value;


// Regular Expressions

const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

const mobilePattern = /^[0-9]{10}$/; // Assumes 10-digit mobile number without country code

// Validate the form and collect errors

if (!name) {

document.getElementById("nameError").textContent = "Name is required.";

errorMessages = true;

if (!gender) {

document.getElementById("genderError").textContent = "Gender is required.";

errorMessages = true;

if (hobbies.length === 0) {

document.getElementById("hobbiesError").textContent = "Please select at least one hobby.";

errorMessages = true;

if (!email || !emailPattern.test(email)) {

document.getElementById("emailError").textContent = "Please enter a valid email address.";

errorMessages = true;

if (!mobile || !mobilePattern.test(mobile)) {

document.getElementById("mobileError").textContent = "Please enter a valid mobile number


(10 digits).";

errorMessages = true;

if (!dob) {

document.getElementById("dobError").textContent = "Date of birth is required.";

errorMessages = true;

}
// If there are any errors, return and prevent form submission

if (errorMessages) {

return;

// If all validations pass, display the results

const output = document.getElementById("output");

output.innerHTML = `<h3>Form Submitted Successfully!</h3>

<p><strong>Name:</strong> ${name}</p>

<p><strong>Gender:</strong> ${gender.value}</p>

<p><strong>Hobbies:</strong> ${hobbies.join(', ')}</p>

<p><strong>Email:</strong> ${email}</p>

<p><strong>Mobile Number:</strong> ${mobile}</p>

<p><strong>Comments:</strong> ${comments}</p>

<p><strong>Date of Birth:</strong> ${dob}</p>`;

</script>

</body>

</html>

Form validation with map function


<!DOCTYPE html>

<html>

<head>

<title>Form Validation Example</title>

<style>

.output { margin-top: 20px; }

.error { color: red; font-size: 0.9em; }

</style>
</head>

<body>

<h2>Form Validation Example</h2>

<form id="myForm">

<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br>

<span id="nameError" class="error"></span><br><br>

<label for="gender">Gender:</label><br>

<input type="radio" id="male" name="gender" value="Male">

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="Female">

<label for="female">Female</label><br>

<span id="genderError" class="error"></span><br><br>

<label for="hobbies">Hobbies:</label><br>

<input type="checkbox" id="reading" name="hobbies" value="Reading">

<label for="reading">Reading</label>

<input type="checkbox" id="sports" name="hobbies" value="Sports">

<label for="sports">Sports</label><br>

<span id="hobbiesError" class="error"></span><br><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br>

<span id="emailError" class="error"></span><br><br>

<label for="mobile">Mobile Number:</label><br>

<input type="text" id="mobile" name="mobile" required><br>

<span id="mobileError" class="error"></span><br><br>


<label for="comments">Comments:</label><br>

<textarea id="comments" name="comments" rows="4" cols="50"></textarea><br><br>

<label for="dob">Date of Birth:</label><br>

<input type="date" id="dob" name="dob" required><br><br>

<span id="dobError" class="error"></span><br><br>

<button type="button" onclick="validateForm()">Submit</button>

</form>

<div id="output" class="output"></div>

<script>

function validateForm() {

// Clear previous errors

document.querySelectorAll('.error').forEach(function(errorSpan) {

errorSpan.textContent = '';

});

let errorMessages = false;

// Get form values

const name = document.getElementById("name").value;

const gender = document.querySelector('input[name="gender"]:checked');

// Collect selected hobbies using map

const hobbies = Array.from(document.querySelectorAll('input[name="hobbies"]:checked'))

.map(checkbox => checkbox.value);

const email = document.getElementById("email").value;


const mobile = document.getElementById("mobile").value;

const comments = document.getElementById("comments").value;

const dob = document.getElementById("dob").value;

// Regular Expressions

const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

const mobilePattern = /^[0-9]{10}$/; // Assumes 10-digit mobile number without country code

// Validate the form and collect errors

if (!name) {

document.getElementById("nameError").textContent = "Name is required.";

errorMessages = true;

if (!gender) {

document.getElementById("genderError").textContent = "Gender is required.";

errorMessages = true;

if (hobbies.length === 0) {

document.getElementById("hobbiesError").textContent = "Please select at least one hobby.";

errorMessages = true;

if (!email || !emailPattern.test(email)) {

document.getElementById("emailError").textContent = "Please enter a valid email address.";

errorMessages = true;

if (!mobile || !mobilePattern.test(mobile)) {

document.getElementById("mobileError").textContent = "Please enter a valid mobile number


(10 digits).";

errorMessages = true;

if (!dob) {
document.getElementById("dobError").textContent = "Date of birth is required.";

errorMessages = true;

// If there are any errors, return and prevent form submission

if (errorMessages) {

return;

// If all validations pass, display the results

const output = document.getElementById("output");

output.innerHTML = `<h3>Form Submitted Successfully!</h3>

<p><strong>Name:</strong> ${name}</p>

<p><strong>Gender:</strong> ${gender.value}</p>

<p><strong>Hobbies:</strong> ${hobbies.join(', ')}</p>

<p><strong>Email:</strong> ${email}</p>

<p><strong>Mobile Number:</strong> ${mobile}</p>

<p><strong>Comments:</strong> ${comments}</p>

<p><strong>Date of Birth:</strong> ${dob}</p>`;

</script>

</body>

</html>

Checkbox calculation
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Grocery List with Amount</title>

</head>

<body>

<h2>Grocery List</h2>

<form id="groceryForm">

<h3>Select Items</h3>

<!-- Item 1 -->

<input type="checkbox" id="apple" value="apple" data-price="1.5">

<label for="apple">Apple - $1.50</label><br>

<!-- Item 2 -->

<input type="checkbox" id="banana" value="banana" data-price="1.0">

<label for="banana">Banana - $1.00</label><br>

<!-- Item 3 -->

<input type="checkbox" id="carrot" value="carrot" data-price="0.75">

<label for="carrot">Carrot - $0.75</label><br>

<!-- Item 4 -->

<input type="checkbox" id="milk" value="milk" data-price="2.0">

<label for="milk">Milk - $2.00</label><br>

<!-- Item 5 -->

<input type="checkbox" id="bread" value="bread" data-price="1.25">

<label for="bread">Bread - $1.25</label><br><br>


<button type="button" onclick="calculateTotal()">Calculate Total</button>

</form>

<h3>Selected Items:</h3>

<ul id="selectedItems"></ul>

<h3>Total Amount: $<span id="totalAmount">0.00</span></h3>

<script>

// Function to calculate the total cost using a for loop

function calculateTotal() {

let totalAmount = 0;

let selectedItems = '';

// Get all checked checkboxes

const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');

// Loop through each checked item using a for loop

for (let i = 0; i < checkboxes.length; i++) {

const checkbox = checkboxes[i];

const itemName = checkbox.value;

const itemPrice = parseFloat(checkbox.getAttribute('data-price'));

totalAmount += itemPrice;

selectedItems += `<li>${itemName} - $${itemPrice.toFixed(2)}</li>`;

// Display selected items

document.getElementById('selectedItems').innerHTML = selectedItems;

// Display total amount

document.getElementById('totalAmount').innerText = totalAmount.toFixed(2);
}

</script>

</body>

</html>

Using reduce method:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Grocery List with Amount</title>

</head>

<body>

<h2>Grocery List</h2>

<form id="groceryForm">

<h3>Select Items</h3>

<!-- Item 1 -->

<input type="checkbox" id="apple" value="apple" data-price="1.5">

<label for="apple">Apple - $1.50</label><br>

<!-- Item 2 -->

<input type="checkbox" id="banana" value="banana" data-price="1.0">

<label for="banana">Banana - $1.00</label><br>

<!-- Item 3 -->


<input type="checkbox" id="carrot" value="carrot" data-price="0.75">

<label for="carrot">Carrot - $0.75</label><br>

<!-- Item 4 -->

<input type="checkbox" id="milk" value="milk" data-price="2.0">

<label for="milk">Milk - $2.00</label><br>

<!-- Item 5 -->

<input type="checkbox" id="bread" value="bread" data-price="1.25">

<label for="bread">Bread - $1.25</label><br><br>

<button type="button" onclick="calculateTotal()">Calculate Total</button>

</form>

<h3>Selected Items:</h3>

<ul id="selectedItems"></ul>

<h3>Total Amount: $<span id="totalAmount">0.00</span></h3>

<script>

// Function to calculate the total cost using reduce()

function calculateTotal() {

let selectedItems = '';

// Get all checked checkboxes

const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');

// Use reduce to calculate the total cost

const totalAmount = Array.from(checkboxes).reduce((total, checkbox) => {

const itemName = checkbox.value;

const itemPrice = parseFloat(checkbox.getAttribute('data-price'));


selectedItems += `<li>${itemName} - $${itemPrice.toFixed(2)}</li>`;

return total + itemPrice;

}, 0);

// Display selected items

document.getElementById('selectedItems').innerHTML = selectedItems;

// Display total amount

document.getElementById('totalAmount').innerText = totalAmount.toFixed(2);

</script>

</body>

</html>

You might also like