使用jQuery Validation Plugin实现价格输入/下拉选择的二选一校验
Got it, let's tackle this validation scenario where users need to either pick a preset price from a dropdown or enter a custom one—no empty submissions allowed. Here's a step-by-step implementation using the jQuery Validation Plugin:
1. Complete Your Form HTML
First, let's flesh out your existing form with proper IDs and names for easier targeting (I've added a preset dropdown and finished the input group):
<form id="priceForm"> <div class="col-sm-12"> <label for="price">Price</label> <div class="form-inline"> <div class="input-group"> <div class="input-group-addon">€</div> <select id="price_select" name="price_select" class="form-control"> <option value="">-- Select a preset price --</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> </div> <span class="text-muted mx-2">or</span> <div class="input-group"> <div class="input-group-addon">€</div> <input type="number" id="price_custom" name="price_custom" class="form-control" placeholder="Enter custom price"> </div> </div> <!-- Container for unified error message --> <div id="price_error" class="text-danger mt-1"></div> </div> <button type="submit" class="btn btn-primary mt-3">Submit</button> </form>
2. Add jQuery Validation Logic
The plugin doesn't have a built-in rule for "at least one field required" between two inputs, so we'll create a custom validation method. Here's the full JavaScript:
$(document).ready(function() { // Custom validation method: Check if either price field has a value $.validator.addMethod("atLeastOnePrice", function(value, element) { const selectedPrice = $("#price_select").val().trim(); const customPrice = $("#price_custom").val().trim(); // Return true if either field is filled return selectedPrice !== "" || customPrice !== ""; }, "Please select a preset price or enter a custom one."); // Initialize form validation $("#priceForm").validate({ rules: { // Apply our custom rule to both fields price_select: { atLeastOnePrice: true }, price_custom: { atLeastOnePrice: true, // Optional: Add extra rules for custom price validity number: true, min: 0.01 } }, messages: { // Customize messages for extra rules price_custom: { number: "Please enter a valid numeric price.", min: "Custom price must be at least €0.01." } }, // Place all price-related errors in a single container errorPlacement: function(error, element) { $("#price_error").html(error); return false; // Prevent default error placement next to each field }, // Handle form submission once valid submitHandler: function(form) { // Replace with your actual submission logic alert("Form validated successfully!"); form.submit(); } }); });
Key Details Explained
- Custom Validation Method:
atLeastOnePricechecks both fields to ensure at least one has a non-empty value. We apply this rule to both the dropdown and custom input so validation triggers no matter which field the user interacts with. - Unified Error Message: Using
errorPlacementensures we don't show duplicate error messages next to both fields—instead, all price-related errors go into a single, clean container. - Optional Extra Rules: For the custom price input, we added
numberandminrules to ensure users enter a valid positive number, which is standard for price fields.
This setup will enforce your requirement: users can't submit the form unless they've either selected a preset price or entered a custom one.
内容的提问来源于stack exchange,提问作者lonerunner

