Content is user-generated and unverified.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Improved jQuery Form Validation</title> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input, select, textarea { width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; } button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #45a049; } .error { color: #d9534f; font-size: 14px; margin-top: 5px; display: none; } input.invalid { border-color: #d9534f; } input.valid { border-color: #5cb85c; } .form-status { padding: 10px; margin: 20px 0; border-radius: 4px; display: none; } .success { background-color: #dff0d8; border: 1px solid #d6e9c6; color: #3c763d; } .failure { background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; } </style> </head> <body> <h1>Contact Form</h1> <div id="formStatus" class="form-status"></div> <form id="myForm"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <div id="nameError" class="error">Please enter your name</div> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" id="email" name="email"> <div id="emailError" class="error">Please enter a valid email address</div> </div> <div class="form-group"> <label for="phone">Phone (optional):</label> <input type="text" id="phone" name="phone"> <div id="phoneError" class="error">Please enter a valid phone number</div> </div> <div class="form-group"> <label for="message">Message:</label> <textarea id="message" name="message" rows="4"></textarea> <div id="messageError" class="error">Please enter a message</div> </div> <button type="submit">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { // Object to track validation state const validationState = { name: false, email: false, phone: true, // Optional field starts as valid message: false }; // Helper function to validate email function isValidEmail(email) { const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailPattern.test(email); } // Helper function to validate phone function isValidPhone(phone) { if (phone.trim() === '') return true; // Optional const phonePattern = /^[\d\s\-\(\)]+$/; return phonePattern.test(phone); } // Validate a specific field function validateField(fieldId) { const value = $(`#${fieldId}`).val().trim(); let isValid = false; switch(fieldId) { case 'name': isValid = value !== ''; break; case 'email': isValid = isValidEmail(value); break; case 'phone': isValid = isValidPhone(value); break; case 'message': isValid = value !== ''; break; } // Update UI based on validation result if (isValid) { $(`#${fieldId}`).removeClass('invalid').addClass('valid'); $(`#${fieldId}Error`).hide(); } else { $(`#${fieldId}`).removeClass('valid').addClass('invalid'); $(`#${fieldId}Error`).show(); } // Update validation state validationState[fieldId] = isValid; return isValid; } // Check if all required fields are valid function isFormValid() { return Object.values(validationState).every(field => field === true); } // Setup real-time validation for each field $('#name, #email, #phone, #message').on('blur', function() { validateField(this.id); }); // Also validate on input changes after first blur $('#name, #email, #phone, #message').on('input', function() { if ($(this).hasClass('invalid')) { validateField(this.id); } }); // Form submission handler $('#myForm').submit(function(event) { event.preventDefault(); // Validate all fields validateField('name'); validateField('email'); validateField('phone'); validateField('message'); if (isFormValid()) { // Form is valid - simulate form submission $('#formStatus') .removeClass('failure') .addClass('success') .html('Form submitted successfully! We will contact you soon.') .show(); // Here you would normally submit the form data to the server // For example: $.ajax({ ... }) or this.submit() // Optional: Reset form after successful submission // $('#myForm')[0].reset(); } else { // Form is invalid $('#formStatus') .removeClass('success') .addClass('failure') .html('Please correct the errors in the form before submitting.') .show(); } }); }); </script> </body> </html>
Content is user-generated and unverified.
    Improved jQuery Form Validation | Claude