-
Getting Started
- Basic Function
- Input File
- Popup
- Forms Validation
Get started with JN Snippets
Step-by-Step Guide to JS Form Validation
-
Step 1: Structure
Wrap each form input element (like `<input>`, `<select>`, `<textarea>`) in a `<label>` with the class jn-input-wrap.
Each input element should be inside its respective `<label>`.// Buttons for Popup <label class="jn-input-wrap"> <input type="text" placeholder="Name" /> </label>
Validation Conditions:
1. Text, Password, Select, Search:
These fields are validated for non-emptiness.
2. Email:
Must be in a valid email format (name@example.com).
3. Phone Number:
Exactly 10 digits are required.
4. URL:
Must start with http:// or https://.
5. Number:
Valid positive integer.
6. File:
Accepts specific file types like PNG, JPG, GIF, PDF.
7. Error Display:
Errors can be shown either by displaying error messages or by highlighting fields with a red outline, controlled by showErrorMessages boolean.
Implementation in JavaScript:
The script attaches a submit event listener to each form.
On form submission, it prevents the default behavior (event.preventDefault()) and validates each field based on its type.
Errors are appended as messages inside the respective label or shown via red outline.
Utility Functions:
Various helper functions (isValidEmail, isValidPhoneNumber, isValidURL, etc.) validate input values against predefined regular expressions. -
Example Implementation:
<!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> </head> <body> <h1 style="text-align: center">Form Validation</h1> <section> <div class="container"> <form> <!-- Your form inputs here --> </form> </div> </section> <script> // Your validation JavaScript code here </script> </body> </html>
-
Javascript
To manage the validation functionality, use the following JavaScript:
// JavaScript Validation Library // Configuration options const showErrorMessages = true; // Set to true to show error messages, false to highlight with red outline only // Function to validate form fields function validateForm(event) { event.preventDefault(); // Prevent form submission initially const form = event.target; // Get the form that was submitted clearErrorMessages(form); clearRedOutlines(form); // Select input wrappers within the current form const inputWraps = form.querySelectorAll(".jn-input-wrap"); let isValid = true; // Iterate over each input wrapper inputWraps.forEach((inputWrap) => { const input = inputWrap.querySelector("input, select, textarea"); if (input) { let inputType; if (input.tagName == "SELECT" || input.tagName == "TEXTAREA") { inputType = input.tagName.toLowerCase(); } else { inputType = input.getAttribute("type"); } const value = input.value.trim(); // Validate based on input type switch (inputType) { case "text": case "password": case "textarea": case "select": case "search": // Added 'search' type if (value === "") { if (showErrorMessages) { appendError(inputWrap, "This field is required."); } else { addRedOutline(input); } isValid = false; } break; case "email": if (!isValidEmail(value)) { if (showErrorMessages) { appendError( inputWrap, "Please enter a valid email address." ); } else { addRedOutline(input); } isValid = false; } break; case "tel": if (!isValidPhoneNumber(value)) { if (showErrorMessages) { appendError( inputWrap, "Please enter a valid phone number (10 digits only)." ); } else { addRedOutline(input); } isValid = false; } break; case "url": if (!isValidURL(value)) { if (showErrorMessages) { appendError(inputWrap, "Please enter a valid URL."); } else { addRedOutline(input); } isValid = false; } break; case "number": if (!isValidNumber(value)) { if (showErrorMessages) { appendError(inputWrap, "Please enter a valid number."); } else { addRedOutline(input); } isValid = false; } break; case "file": const file = input.files[0]; if (!isValidFile(file)) { if (showErrorMessages) { appendError( inputWrap, "Please upload a valid file (PNG, JPG, GIF, PDF)." ); } else { addRedOutline(input); } isValid = false; } break; case "date": case "time": if (value === "") { if (showErrorMessages) { appendError(inputWrap, "This field is required."); } else { addRedOutline(input); } isValid = false; } break; case "radio": case "checkbox": const name = input.getAttribute("name"); const group = document.querySelectorAll(`input[name="${name}"]`); const isChecked = Array.from(group).some((radio) => radio.checked); if (!isChecked) { if (showErrorMessages) { appendError(inputWrap, "This option must be checked."); } else { group.forEach(radio => addRedOutline(radio)); } isValid = false; } break; default: break; } } }); // If form is valid, submit it if (isValid) { event.target.submit(); } } // Function to clear error messages within a specific form function clearErrorMessages(form) { const errorMessages = form.querySelectorAll(".jn-input-wrap .error-message"); errorMessages.forEach((errorMessage) => { errorMessage.remove(); }); } // Function to append error message to input wrapper function appendError(inputWrap, errorMessageText) { const errorMessage = document.createElement("div"); inputWrap.classList.add("error-wrap"); errorMessage.classList.add("error-message"); errorMessage.textContent = errorMessageText; inputWrap.appendChild(errorMessage); } // Function to add red outline to input function addRedOutline(input) { // input.classList.add("error-outline"); input.style.setProperty("outline", "1px solid #ff2200", "important"); } // Function to clear red outlines within a specific form function clearRedOutlines(form) { const inputs = form.querySelectorAll(".jn-input-wrap input, .jn-input-wrap select, .jn-input-wrap textarea"); inputs.forEach((input) => { input.style.removeProperty("outline"); }); } // Validation functions for specific input types function isValidEmail(email) { // Regular expression for basic email validation const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } function isValidPhoneNumber(phone) { // Regular expression to match 10 digit phone number const phoneRegex = /^\d{10}$/; return phoneRegex.test(phone); } function isValidURL(url) { // Regular expression for basic URL validation const urlRegex = /^(ftp|http|https):\/\/[^ "]+$/; return urlRegex.test(url); } function isValidNumber(number) { // Regular expression for integer number validation const numberRegex = /^\d+$/; return numberRegex.test(number); } function isValidFile(file) { // Check file type (example checks for PNG, JPG, GIF, PDF) if (!file) return false; const fileType = file.type; return ( fileType === "image/png" || fileType === "image/jpeg" || fileType === "image/gif" || fileType === "application/pdf" ); } // Attach validation function to form submit event const forms = document.querySelectorAll("form"); forms.forEach((form) => { form.addEventListener("submit", validateForm); });