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

Vue.js动态表单字段验证优化:用循环替换冗余if-else

表单动态验证优化:替换冗余if-else为循环实现

问题描述

我知道这是常见问题,但仍困惑如何为每个表单字段实现动态验证。目前我在每个字段中使用if else condition进行判断,这并非合理实现方式。我希望将验证逻辑放入循环中,当字段为空值时能识别出具体的空字段,请问是否可行?

验证效果图片

我的表单

<b-form class="needs-validation" @submit="onCustomStyleSubmit" >
<div class="form-row" >
    <div class="col-md-4 mb-3"  >
        <label for="c_form_cluster">Cluster</label>
        <b-form-input type="text" id="c_form_cluster" v-model="c_form.cluster" :state="c_form_result.cluster"  placeholder="Cluster"></b-form-input>
        <b-form-valid-feedback :state="c_form_result.cluster">Lock Good</b-form-valid-feedback>
    </div>
    <div class="col-md-4 mb-3">
        <label for="c_form_lbp">LBP</label>
        <b-form-input type="text" id="c_form_lbp" v-model="c_form.lbp" :state="c_form_result.lbp" placeholder="LBP"></b-form-input>
        <b-form-valid-feedback :state="c_form_result.lbp">Lock Good</b-form-valid-feedback>
    </div>
    <div class="col-md-4 mb-3">
        <label for="c_form_amt_certified">Amount Certified</label>
        <b-input-group prepend="0.00">
            <b-form-input type="number" id="c_form_amt_certified" v-model="c_form.amt_certified" :state="c_form_result.amt_certified" placeholder="amount"></b-form-input>
        </b-input-group>
        <b-form-invalid-feedback :state="c_form_result.amt_certified">Please choose a unique and valid amt_certified.</b-form-invalid-feedback>
    </div>
</div>
<div class="form-row">
    <div class="col-md-4 mb-3">
        <label for="c_form_fund">Fund 101</label>
        <b-form-input type="text" id="c_form_fund" v-model="c_form.fund" :state="c_form_result.fund" placeholder="Fund"></b-form-input>
        <b-form-invalid-feedback :state="c_form_result.fund">Please provide a valid fund.</b-form-invalid-feedback>
    </div>
    <div class="col-md-4 mb-3">
        <label for="c_form_state">Status</label>
        <b-form-input type="text" id="c_form_state" v-model="c_form.state" :state="c_form_result.state" placeholder="TE"></b-form-input>
        <b-form-invalid-feedback :state="c_form_result.state">Please provide a valid state.</b-form-invalid-feedback>
    </div>
    <div class="col-md-4 mb-3">
        <label for="c_form_employeecode">Employee</label>
        <b-form-input type="text" id="c_form_employeecode" v-model="c_form.employee" :state="c_form_result.employee" placeholder="Employee"></b-form-input>
        <b-form-invalid-feedback :state="c_form_result.employee">Please provide a valid employee.</b-form-invalid-feedback>
    </div>
</div>
    <div class="form-row">
    <div class="col-md-4 mb-3">
        <label for="c_form_fund">Province</label>
        <div class="form-group">
          <b-form-select v-model="c_form.province" :options="province_select_options" :state="c_form_result.province"></b-form-select>
          <b-form-invalid-feedback :state="c_form_result.province">Don't leave this blank</b-form-invalid-feedback>
        </div>

    </div>
    <div class="col-md-4 mb-3">
        <label for="c_form_fund">Municipality</label>
        <div class="form-group">
          <b-form-select v-model="c_form.municipality" :options="municipality_select_options" :state="c_form_result.municipality" placeholder="Municipality"></b-form-select>
          <b-form-invalid-feedback :state="c_form_result.municipality">Don't leave this blank</b-form-invalid-feedback>
        </div>

    </div>
      <div class="col-md-4 mb-3">
        <label for="c_form_fund">Barangay</label>
        <div class="form-group">
          <b-form-select v-model="c_form.barangay" :options="barangay_select_options" :state="c_form_result.barangay" placeholder="Barangay"></b-form-select>
          <b-form-invalid-feedback :state="c_form_result.barangay">Don't leave this blank</b-form-invalid-feedback>
        </div>
    </div>
</div>
<b-button type="submit" variant="secondary">Generate Transaction Number</b-button>
</b-form>

我的脚本文件

<script>
  export default {
    data(){
      return{
        c_form: 
        {
          cluster:'',
          lbp:'',
          amt_certified:'',
          fund:'',
          state:'',
          employee:'',
          province:'',
          municipality:'',
          barangay:'',
          qrcode:''
        },
  
      c_form_result:{
          cluster:null,
          lbp:null,
          amt_certified:null,
          fund:null,
          state:null,
          employee:null,
          province:null,
          municipality:null,
          barangay:null,
          qrcode:null
        },
        province_select_options: [
          { value: null, text:'Select Province' },
          { value: '1', text:'Agusan Del Norte' },
          { value: '2', text:'Agusan Del Sur' },
          { value: '3', text:'Surigao Del Norte' },
          { value: '4', text:'Surigao Del Sur' },
          { value: '5', text:'Dinagat Islands' }
        ],
        municipality_select_options: [
          { value: null, text:'Select Municipality' },
          { value: '1', text:'Butuan City' },
          { value: '2', text:'Cabadbaran' },
          { value: '3', text:'Lianga' },
          { value: '4', text:'Cantillan' },
          { value: '5', text:'Siargao' }
        ],
        barangay_select_options: [
          { value: null, text:'Barangay' },
          { value: '1', text:'J.P. Rizal' },
          { value: '2', text:'Maon' },
          { value: '3', text:'Mahogany' },
          { value: '4', text:'Villakananga' },
          { value: '5', text:'Poblacion' }
        ],
        //end table
      };
    },
    methods:{
    onCustomStyleSubmit(evt){  
        evt.preventDefault();
        // this.onSelectedItems();
        let cluster = this.c_form.cluster;
        let lbp = this.c_form.lbp;
        let amt_certified = this.c_form.amt_certified;
        let fund = this.c_form.fund;
        let state = this.c_form.state;
        let employee = this.c_form.employee;
        let province = this.c_form.province;
        let municipality = this.c_form.municipality;
        let barangay = this.c_form.barangay;

        if(cluster !== '') {
          this.c_form_result.cluster = true;
        } else {

          this.c_form_result.cluster = false;
        }
        if(lbp !== '') {
          this.c_form_result.lbp = true;
        } else {
          this.c_form_result.lbp = false;
        }

        if(amt_certified!== '') {
          this.c_form_result.amt_certified = true;
        } else {
          this.c_form_result.amt_certified = false;
        }

        if(fund!== '') {
          this.c_form_result.fund = true;
        } else {
          this.c_form_result.fund = false;
        }

        if(state !== '') {
          this.c_form_result.state = true;
        } else {
          this.c_form_result.state = false;
        }

        if(province !== '') {
          this.c_form_result.province = true;
        } else {
          this.c_form_result.province = false;
        }

        if(municipality !== '') {
          this.c_form_result.municipality = true;
        } else {
          this.c_form_result.municipality = false;
        }

        if(employee !== '') {
          this.c_form_result.employee = true;
        } else {
          this.c_form_result.employee = false;
        }

        if(barangay !== '') {
          this.c_form_result.barangay = true;
        } else if(this.c_form.barangay == '') {
          this.c_form_result.barangay = false;
        }

        console.log(this.c_form);
      },
    }
  };
</script>

解决方案:用循环实现统一验证

完全可行,你可以通过遍历表单字段的方式替代冗余的if-else判断,代码更简洁且易维护。核心思路是:

  1. 获取c_form对象的所有字段名
  2. 循环遍历每个字段,判断字段值是否为空(覆盖输入框空字符串、下拉框null的情况)
  3. 同步更新c_form_result中对应字段的验证状态

修改后的onCustomStyleSubmit方法

onCustomStyleSubmit(evt){  
    evt.preventDefault();
    // 遍历c_form的所有字段
    Object.keys(this.c_form).forEach(field => {
        // 排除不需要验证的字段(比如qrcode)
        if (field === 'qrcode') return;
        // 判断字段值是否为空:空字符串或null都视为未填写
        const isFilled = this.c_form[field] !== '' && this.c_form[field] !== null;
        // 更新对应验证状态
        this.c_form_result[field] = isFilled;
    });
    console.log(this.c_form);
}

代码说明

  • Object.keys(this.c_form):获取表单对象的所有属性名(即字段名)
  • 循环中跳过qrcode字段(因为你的表单里没有这个输入项,不需要验证)
  • 空值判断同时覆盖输入框的空字符串和下拉框的默认null值,确保所有必填字段都被验证
  • 直接通过字段名动态访问c_form和c_form_result的属性,避免重复写每个字段的判断逻辑

如果后续需要添加新字段,只需在c_form和c_form_result中新增对应属性,验证逻辑无需修改,扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 08:15:41