You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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/else block targets a unique input type with tailored validation:
    • text: Ensures the field isn't empty
    • email: Uses a regex to validate standard email format
    • password: Checks for minimum length
    • number: Verifies it's a valid number and meets a minimum value
    • checkbox: Ensures the user has agreed to terms
  • Reusable Helper: The markAsInvalid function keeps error handling consistent across all fields.
  • Extensible: You can easily add more else if blocks for other input types (like tel for phone numbers) or extra rules (like password strength checks).

内容的提问来源于stack exchange,提问作者Husna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:48:41