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

如何在不使用Validation Engine的情况下批量验证jQuery表单字段

不依赖Validation Engine的表单批量验证实现

问题场景

现有如下表单,需要实现所有字段的统一批量验证,避免逐个字段写重复判断逻辑:

原始HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="radio_error" style="display:none;">Please select any field</div>
<div class="select-type">
    <div class="radio">
        <input  type="radio" name="selct-type" value="sell"/><label>Sell </label>
    </div>
    <div class="radio">
        <input  type="radio" name="selct-type" value="auction"/><label>Auction </label>
    </div>
</div>

<div id="price_error" style="display:none;">Please enter your price</div>
<input class="form-control" placeholder="Price" id="priice" name="price" type="number" />

<div id="quantity_error" style="display:none;">Please enter quantity</div>
<input class="form-control" id="number" placeholder="quanity" type="number" name="quantity"/>
<input type="submit" name="listing" value="Complete listing" onclick="completeListing(this)" >

原始JS代码

async function completeListing(elm)
{
    var type= $("input[name='selct-type']:checked").val();
    var quantity= $("#number").val();
    var price= $("#priice").val();
    if(type=="")
        {
            $("#radio_error").show();
        }
    if(price=="")
        {
            $("#price_error").show();
        }
    if(quantity=="")
        {
            $("#quantity_error").show();
        }
    else
        {
            //further code
        }   
}

批量验证优化方案

通过配置化验证规则实现批量验证,核心是把每个字段的验证逻辑、错误提示元素统一存入配置数组,循环遍历执行验证,后续新增字段只需添加配置,无需修改核心逻辑。

优化后的JS代码

async function completeListing(elm) {
    // 先隐藏所有错误提示
    $('.error-message').hide();

    // 验证规则配置:每个字段对应验证逻辑、错误提示元素
    const validationRules = [
        {
            // 单选框验证:判断是否有选中项
            validate: () => $("input[name='selct-type']:checked").length > 0,
            errorElement: $('#radio_error')
        },
        {
            // 价格验证:判断是否为空
            validate: () => $.trim($("#priice").val()) !== '',
            errorElement: $('#price_error')
        },
        {
            // 数量验证:判断是否为空
            validate: () => $.trim($("#number").val()) !== '',
            errorElement: $('#quantity_error')
        }
    ];

    // 批量执行验证
    let isValid = true;
    validationRules.forEach(rule => {
        if (!rule.validate()) {
            rule.errorElement.show();
            isValid = false;
        }
    });

    // 验证通过后执行后续逻辑
    if (isValid) {
        // further code
        console.log('表单验证通过,执行后续操作');
    }
}

配套HTML调整(可选)

给所有错误提示元素添加统一类名,方便批量隐藏:

<div id="radio_error" class="error-message" style="display:none;">Please select any field</div>
<div id="price_error" class="error-message" style="display:none;">Please enter your price</div>
<div id="quantity_error" class="error-message" style="display:none;">Please enter quantity</div>

扩展说明

  • 若需添加更复杂的验证规则(如数值范围、格式校验),只需在validationRules数组中新增配置项,比如价格必须大于0:
    {
        validate: () => {
            const price = $.trim($("#priice").val());
            return price !== '' && parseFloat(price) > 0;
        },
        errorElement: $('#price_error')
    }
    
  • 还可给配置项添加错误提示文本字段,动态修改提示内容,进一步提升灵活性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:40:30