const nameInput = document.getElementById("name");
const mobileInput = document.getElementById("mobile");
const emailInput = document.getElementById("email");
const errorElement = document.getElementById("error");
const submitButton = document.getElementById("submit");
const contactsTableBody = document.querySelector("#summaryTable tbody");
const noResultElement = document.getElementById("noResult");
const searchInput = document.getElementById("search");
const nameColumnButton = document.getElementById("nameColumn");
let contacts = [
{
name: "Admin",
mobile: "9999999999",
email: "admin@xyzcompany.com",
},
];
function validateInput(name, mobile, email) {
if (!/^[A-Za-z\s]{1,20}$/.test(name)) {
return "Name should contain only letters and spaces, and be up to 20 characters long.";
}
if (!/^\d{10}$/.test(mobile)) {
return "Mobile number should be exactly 10 digits.";
}
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(email)) {
return "Invalid email address.";
}
return "";
}
function addContactToTable(contact) {
const newRow = contactsTableBody.insertRow();
newRow.insertCell(0).textContent = contact.name;
newRow.insertCell(1).textContent = contact.mobile;
newRow.insertCell(2).textContent = contact.email;
}
function displayContacts(filteredContacts) {
contactsTableBody.innerHTML = "";
if (filteredContacts.length === 0) {
noResultElement.style.display = "block";
} else {
noResultElement.style.display = "none";
filteredContacts.forEach((contact) => addContactToTable(contact));
}
}
submitButton.addEventListener("click", function (event) {
event.preventDefault();
const name = nameInput.value;
const mobile = mobileInput.value;
const email = emailInput.value;
const validationError = validateInput(name, mobile, email);
if (validationError) {
errorElement.textContent = validationError;
errorElement.style.display = "block";
return;
}
const newContact = { name, mobile, email };
contacts.push(newContact);
displayContacts(contacts);
nameInput.value = "";
mobileInput.value = "";
emailInput.value = "";
errorElement.style.display = "none";
});
searchInput.addEventListener("input", function () {
const searchValue = searchInput.value.trim();
const filteredContacts = contacts.filter((contact) =>
contact.mobile.includes(searchValue),
);
displayContacts(filteredContacts);
});
nameColumnButton.addEventListener("click", function () {
const sortedContacts = contacts
.slice()
.sort((a, b) => a.name.localeCompare(b.name));
displayContacts(sortedContacts);
});
displayContacts(contacts);