Skip to content

Instantly share code, notes, and snippets.

@Aminigbo
Last active December 4, 2024 11:29
Show Gist options
  • Save Aminigbo/4c9b66866ea0bf81631bc2548d66348c to your computer and use it in GitHub Desktop.
Save Aminigbo/4c9b66866ea0bf81631bc2548d66348c to your computer and use it in GitHub Desktop.
Explanation :
Class-Based Structure:
The FormHandler class encapsulates all the logic for validation, modal handling, and local storage.
Dynamic Validation:
The validateField method dynamically validates fields based on their names, allowing easy extension.
Centralized Error Handling:
Errors for each field are stored in an errorMessages object, which is used to update the UI.
Reusability:
Modularized methods (like validateAllFields, saveDataToLocalStorage, and showModal) make the code reusable and easy to maintain.
Scalability:
Adding new fields is as simple as extending the fields array and defining validation rules in validateField.
Local Storage Integration:
On successful validation, the form data is stored in localStorage.
This implementation is more professional and easily adaptable to complex requirements. Let me know if you need additional enhancements!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
max-width: 400px;
margin: auto;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
font-weight: bold;
}
input {
width: 100%;
padding: 8px;
margin-top: 5px;
box-sizing: border-box;
}
.error {
color: red;
font-size: 0.875rem;
margin-top: 5px;
}
.success-modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: #f0f8ff;
border: 1px solid #ccc;
border-radius: 8px;
text-align: center;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.modal-header {
font-size: 1.25rem;
font-weight: bold;
margin-bottom: 10px;
}
.modal-close {
margin-top: 15px;
padding: 8px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form id="registrationForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<div id="nameError" class="error"></div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="email">
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" id="phone" name="phone">
<div id="phoneError" class="error"></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password">
<div id="passwordError" class="error"></div>
</div>
<button type="button" onclick="formHandler.validateAndSubmit()">Submit</button>
</form>
<div id="successModal" class="success-modal">
<div class="modal-header">Success</div>
<p>Your form has been submitted successfully!</p>
<button class="modal-close" onclick="formHandler.closeModal()">Close</button>
</div>
<script>
class FormHandler {
constructor(formId, modalId) {
this.form = document.getElementById(formId);
this.modal = document.getElementById(modalId);
this.errorMessages = {};
}
validateField(fieldName, value) {
switch (fieldName) {
case 'name':
if (!value || value.length < 3) {
return 'Name must be at least 3 characters.';
}
break;
case 'email':
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!value || !emailPattern.test(value)) {
return 'Enter a valid email address.';
}
break;
case 'phone':
const phonePattern = /^[0-9]{10,15}$/;
if (!value || !phonePattern.test(value)) {
return 'Enter a valid phone number (10-15 digits).';
}
break;
case 'password':
if (!value || value.length < 6) {
return 'Password must be at least 6 characters.';
}
break;
default:
return '';
}
return '';
}
validateAllFields() {
const fields = ['name', 'email', 'phone', 'password'];
let isValid = true;
fields.forEach(field => {
const input = document.getElementById(field);
const errorElement = document.getElementById(`${field}Error`);
const errorMessage = this.validateField(field, input.value.trim());
if (errorMessage) {
errorElement.textContent = errorMessage;
this.errorMessages[field] = errorMessage;
isValid = false;
} else {
errorElement.textContent = '';
delete this.errorMessages[field];
}
});
return isValid;
}
saveDataToLocalStorage() {
const formData = {
name: document.getElementById('name').value.trim(),
email: document.getElementById('email').value.trim(),
phone: document.getElementById('phone').value.trim(),
password: document.getElementById('password').value.trim(),
};
localStorage.setItem('formData', JSON.stringify(formData));
}
showModal() {
this.modal.style.display = 'flex';
}
closeModal() {
this.modal.style.display = 'none';
}
validateAndSubmit() {
const isValid = this.validateAllFields();
if (isValid) {
this.saveDataToLocalStorage();
this.showModal();
}
}
}
const formHandler = new FormHandler('registrationForm', 'successModal');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment