基于jQuery的无插件表单验证:按input type用if/else实现
Custom jQuery Form Validation (No Plugins, Using if/else)
Hey there! Let's build a fully functional form validation system using plain jQuery—no extra plugins needed. We'll use if/else checks based on each input's type attribute to validate different field types properly. Here's a complete, ready-to-use implementation:
Step 1: The HTML Form
First, let's set up a sample form with common input types. We'll add a data-error attribute to each field to store custom error messages, plus containers for error feedback:
<form id="myForm"> <div class="form-group"> <label for="username">Username:</label> <input type="text" id="username" name="username" data-error="Username cannot be empty"> <span class="error-message"></span> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" id="email" name="email" data-error="Please enter a valid email address"> <span class="error-message"></span> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" id="password" name="password" data-error="Password must be at least 8 characters"> <span class="error-message"></span> </div> <div class="form-group"> <label for="age">Age:</label> <input type="number" id="age" name="age" data-error="Please enter a valid number (18+)"> <span class="error-message"></span> </div> <div class="form-group"> <label> <input type="checkbox" id="terms" name="terms" data-error="You must agree to the terms"> I agree to the terms and conditions </label> <span class="error-message"></span> </div> <button type="submit">Submit</button> </form>
Add basic CSS to highlight errors visually:
.error-message { color: #dc3545; font-size: 0.875rem; display: block; margin-top: 0.25rem; } .form-group.error input { border-color: #dc3545; }
Step 2: The jQuery Validation Logic
Now let's write the core validation code. We'll hook into the form's submit event, loop through each input, validate based on its type, and handle error states:
$(document).ready(function() { $('#myForm').on('submit', function(e) { // Stop default form submission first e.preventDefault(); // Reset all existing errors $('.form-group').removeClass('error'); $('.error-message').text(''); let isFormValid = true; // Loop through every input in the form $(this).find('input').each(function() { const $input = $(this); const inputType = $input.attr('type'); const inputValue = $input.val().trim(); const errorMessage = $input.data('error'); const $formGroup = $input.closest('.form-group'); const $errorSpan = $formGroup.find('.error-message'); // Validate based on input type if (inputType === 'text') { if (inputValue === '') { markAsInvalid($formGroup, $errorSpan, errorMessage); isFormValid = false; } } else if (inputType === 'email') { // Basic regex for email validation const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(inputValue)) { markAsInvalid($formGroup, $errorSpan, errorMessage); isFormValid = false; } } else if (inputType === 'password') { if (inputValue.length < 8) { markAsInvalid($formGroup, $errorSpan, errorMessage); isFormValid = false; } } else if (inputType === 'number') { const numValue = parseInt(inputValue); if (isNaN(numValue) || numValue < 18) { markAsInvalid($formGroup, $errorSpan, errorMessage); isFormValid = false; } } else if (inputType === 'checkbox') { if (!$input.is(':checked')) { markAsInvalid($formGroup, $errorSpan, errorMessage); isFormValid = false; } } // Add more input types (like tel, date) here as needed }); // If all fields are valid, proceed with submission if (isFormValid) { alert('Form submitted successfully!'); // Uncomment below to submit the form normally // this.submit(); } }); // Helper function to mark fields as invalid function markAsInvalid($formGroup, $errorSpan, message) { $formGroup.addClass('error'); $errorSpan.text(message); } });
Key Details to Note
- Error Reset: We clear all previous errors on submit so users don't see stale feedback.
- Type-Specific Rules: Each
if/elseblock targets a unique input type with tailored validation:text: Ensures the field isn't emptyemail: Uses a regex to validate standard email formatpassword: Checks for minimum lengthnumber: Verifies it's a valid number and meets a minimum valuecheckbox: Ensures the user has agreed to terms
- Reusable Helper: The
markAsInvalidfunction keeps error handling consistent across all fields. - Extensible: You can easily add more
else ifblocks for other input types (liketelfor phone numbers) or extra rules (like password strength checks).
内容的提问来源于stack exchange,提问作者Husna
相关产品推荐
相关产品推荐

