vue中自定义form表单字段验证

2022-09-13 05:11:00 by wst

vue

在解决实际问题过程中,总会遇到各种各样的问题。

比如:编辑商品的时候,需要添加规格,但是规格又要动态添加。提交后还要验证。

验证逻辑:“商品规格”至少要添加一个规格,且添加的规格任一项都不能为空。

界面:代码:

<template>
  <div>
    <!-- 导航条 -->
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-goods"></i> 商品管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>我的商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">

      <el-form ref="form" :model="form" label-width="70px" :rules="rules">
        <el-form-item label="商品ID" prop="id">
          <el-input v-model="form.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="商品名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <!-- 规格编辑-->
        <el-form-item label="商品规格" prop="specification" required>
          <el-table
              :data="form.specification"
              stripe>
            <el-table-column
                align="center"
                prop="attr_value"
                label="规格名称"
                width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.attr_value"
                          placeholder="规格名称"
                          type="textarea"
                          autosize
                          class="handle-input-big"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="sku"
                label="规格编号"
                width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sku"
                          placeholder="规格编号"
                          class="handle-input-big"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="price"
                label="价格"
                width="100">
              <template slot-scope="scope">
                <CurrencyInput
                    v-model="scope.row.price"
                    placeholder="价格"
                    class="inline-input"
                    :options="{ currency: 'CNY' }"/>
              </template>

            </el-table-column>
            <el-table-column
                align="center"
                prop="origin_price"
                label="原价"
                width="100"
            >
              <template slot-scope="scope">
                <CurrencyInput
                    v-model="scope.row.origin_price"
                    placeholder="原价"
                    class="inline-input"
                    :options="{ currency: 'CNY' }"/>
              </template>

            </el-table-column>
            <el-table-column
                align="center"
                prop="cost"
                label="成本"
                width="100"
            >
              <template slot-scope="scope">
                <CurrencyInput
                    v-model="scope.row.cost"
                    placeholder="成本"
                    class="inline-input"
                    :options="{ currency: 'CNY' }"/>
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="stock"
                label="库存"
                width="100"
            >
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.stock" placeholder="库存" class="inline-input"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot="header" slot-scope="scope">
                <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click="addItem"
                >增加
                </el-button>
              </template>

              <template slot-scope="scope">
                <el-button
                    type="text"
                    icon="el-icon-delete"
                    class="red"
                    @click="deleteItem(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </div>

  </div>
</template>

<script>
import CurrencyInput from '../common/CurrencyInput'

export default {
  name: "basetable",
  components: {CurrencyInput},
  data() {
    // 自定义校验规则
    var checkSpec = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('规格不能为空'));
      }
      setTimeout(() => {
        if (value.length > 0){
          for(let rec of value){
            for(let key in rec){
              if(!rec[key]){
                callback(new Error('请完善规格的所有字段'))
              }
            }
          }
          callback()
        } else {
          callback(new Error('请至少添加一种规格'))
        }
      }, 500);
    };

    return {
      form: {
        id: null,
        name: '',
        specification: []
      },
      baseSpec: {
        attr_value: '',
        price: null,
        origin_price: null,
        stock: null,
        cost: null,
        sku: ''
      },

      // 编辑框校验规则
      rules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
          {min: 3, max: 100, message: '长度在3-100个字符', trigger: 'blur'}
        ],
        specification: [
            { required: true, message: '请增加规格', trigger: 'change' },
            {validator: checkSpec, trigger: 'change'}
          ],

      }
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 删除规格
    deleteItem(index, item) {
      this.form.specification.splice(index, 1)
    },

    // 增加规格
    addItem() {
      var obj = JSON.parse(JSON.stringify(this.baseSpec))
      this.form.specification.push(obj)
    },

    // 添加记录操作
    handleAdd(index, row) {
      this.form.file = null;
      this.editVisible = true;
    },

    // 保存编辑, 同时提交到后台
    saveEdit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log("校验通过")
          this.$message.success("校验通过")
          return true
        } else {
          console.log('error submit!!');
          this.$confirm("提交错误,请检查输入", "提示", {
            type: "warning",
          })
          return false;
        }
      });
    },


  },
};
</script>

<style scoped>


.inline-input {
  width: 80px;
}

.handle-input-big {
  width: 100px;
}

.red {
  color: #ff0000;
}



</style>

 


Comments(130) Add Your Comment

Ptfpvs
lipitor us <a href="https://lipiws.top/">buy lipitor pills for sale</a> purchase lipitor online cheap
Nqosqs
ciprofloxacin tablet - <a href="https://cipropro.top/bactrimos/">purchase bactrim generic</a> order amoxiclav pills
Drdxbr
buy cheap ciprofloxacin - <a href="https://metroagyl.top/cefaclor/">buy cephalexin without prescription</a> buy clavulanate without a prescription
Xntaou
buy generic ciprofloxacin 500mg - <a href="https://septrim.top/doryx/">buy doxycycline tablets</a> erythromycin for sale
Nsxlkm
buy flagyl sale - <a href="https://metroagyl.top/azithromycin/">zithromax 250mg over the counter</a> order azithromycin 250mg
Alutoc
ivermectin online - <a href="https://keflexin.top/sumycin/">buy generic sumycin over the counter</a> purchase tetracycline sale
Drctma
purchase valtrex without prescription - <a href="https://gnantiviralp.com/diltiazem/">buy diltiazem cheap</a> order acyclovir pills
Wrvefl
ampicillin order <a href="https://ampiacil.top/penicillinused/">order generic penicillin</a> buy amoxil sale
Ziyddc
metronidazole 200mg pill - <a href="https://metroagyl.top/clindamycin/">buy clindamycin without a prescription</a> azithromycin 500mg pill
Popzrb
buy furosemide 100mg generic - <a href="https://antipathogenc.com/capoten/">capoten 25 mg drug</a> capoten sale
Mhkbkq
glycomet for sale - <a href="https://gnantiacidity.com/lincocin/">buy lincomycin 500 mg without prescription</a> order lincocin sale
Lxgarm
buy retrovir 300 mg - <a href="https://canadiangnp.com/rulide/">buy roxithromycin medication</a> where to buy zyloprim without a prescription
Omaglz
buy clozaril pill - <a href="https://genonlinep.com/">cheap clozapine 100mg</a> buy pepcid 20mg for sale
Vrodzy
seroquel 50mg drug - <a href="https://gnkantdepres.com/effexor/">buy venlafaxine 75mg generic</a> cheap eskalith without prescription
Mahybg
clomipramine 25mg brand - <a href="https://antdeponline.com/sinequan/">order generic sinequan 25mg</a> order doxepin 25mg for sale
Opmahc
buy hydroxyzine 10mg pills - <a href="https://antdepls.com/prozac/">order sarafem 40mg without prescription</a> buy generic endep over the counter
Cvotpr
order augmentin 375mg online cheap - <a href="https://atbioinfo.com/ciprofloxacin/">cipro sale</a> order cipro 500mg pills
Pnuhck
cheap amoxil sale - <a href="https://atbioxotc.com/trimox/">order trimox 250mg online</a> order cipro 1000mg online
Ckhgsq
how to buy azithromycin - <a href="https://gncatbp.com/btetracycline/">buy generic tetracycline</a> ciplox online
Swijuc
clindamycin canada - <a href="https://cadbiot.com/doxycycline/">vibra-tabs brand</a> buy chloramphenicol generic
Uaqoxq
ivermectin 6mg pills for humans - <a href="https://antibpl.com/">cheap stromectol</a> cefaclor 250mg oral
Qdwxve
ventolin 2mg drug - <a href="https://antxallergic.com/oiphenergan/">where to buy phenergan without a prescription</a> theo-24 Cr us
Ujpxcn
buy methylprednisolone tablets - <a href="https://ntallegpl.com/loratadine/">buy claritin 10mg sale</a> order astelin generic
Ibwokv
desloratadine for sale online - <a href="https://rxtallerg.com/beclomethasone/">beclomethasone canada</a> albuterol inhalator without prescription
Iiqldq
buy micronase for sale - <a href="https://prodeprpl.com/pioglitazone30/">cheap actos</a> buy generic forxiga for sale
Mrnfry
buy metformin generic - <a href="https://arxdepress.com/acarbose50/">precose generic</a> buy precose 50mg online cheap
Juntkt
purchase prandin for sale - <a href="https://depressinfo.com/jardiance25/">where can i buy jardiance</a> buy jardiance pills for sale
Ajbqvg
rybelsus for sale online - <a href="https://infodeppl.com/ddavpspray/">buy generic desmopressin for sale</a> buy DDAVP for sale
Skvnbl
order lamisil 250mg online cheap - <a href="https://treatfungusx.com/">terbinafine 250mg usa</a> buy griseofulvin generic
Znwgen
nizoral buy online - <a href="https://antifungusrp.com/">nizoral 200 mg uk</a> sporanox order
Ihajkw
famvir 500mg for sale - <a href="https://amvinherpes.com/">famciclovir oral</a> valcivir 1000mg tablet
Gblutc
digoxin online order - <a href="https://blpressureok.com/dipyridamole100/">buy generic dipyridamole 25mg</a> furosemide 100mg tablet
Amewgh
lopressor sale - <a href="https://bloodpresspl.com/telmisartan/">order telmisartan online</a> nifedipine order
Xqudxw
purchase hydrochlorothiazide sale - <a href="https://norvapril.com/lisinopril/">zestril pills</a> bisoprolol 5mg drug
Ddsuqt
buy nitroglycerin generic - <a href="https://nitroproxl.com/indapamide/">buy lozol online</a> order valsartan 160mg sale
Myftlc
buy generic simvastatin over the counter - <a href="https://canescholest.com/atorvastatin/">atorvastatin claw</a> atorvastatin carter
Enneon
rosuvastatin gain - <a href="https://antcholesterol.com/caduet5mg/">caduet pills original</a> caduet pills note
Aigasp
viagra professional traffic - <a href="https://edsildps.com/eriacta/">eriacta bold</a> levitra oral jelly rib
Vxuvve
dapoxetine increase - <a href="https://promedprili.com/fildena/">fildena enormous</a> cialis with dapoxetine clad
Zuecct
cenforce online relieve - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra such
Vsyshb
brand cialis slant - <a href="https://probrandtad.com/penisole/">penisole bear</a> penisole gather
Ifodgp
brand cialis proof - <a href="https://probrandtad.com/zhewitra/">zhewitra near</a> penisole dizzy
Utkchi
cialis soft tabs online pose - <a href="https://supervalip.com/tadarisepills/">tadarise pills cupboard</a> viagra oral jelly pierce
Nxtkjf
cialis soft tabs file - <a href="https://supervalip.com/cavertapills/">caverta pills faith</a> viagra oral jelly online river
Wkfbmu
priligy often - <a href="https://promedprili.com/aurogra/">aurogra band</a> cialis with dapoxetine current
Qfnzou
cenforce online curl - <a href="https://xcenforcem.com/kamagrasildenafil/">kamagra pills craft</a> brand viagra online start
Gsoeig
asthma treatment realize - <a href="https://bsasthmaps.com/">asthma treatment mistaken</a> asthma medication release
Bsqrbl
acne treatment would - <a href="https://placnemedx.com/">acne medication trickle</a> acne medication offend
Ocmarn
prostatitis treatment soul - <a href="https://xprosttreat.com/">pills for treat prostatitis lawn</a> prostatitis pills steep
Rmciog
treatment for uti snake - <a href="https://amenahealthp.com/">uti antibiotics part</a> uti medication too
Rxbwnq
claritin pills escape - <a href="https://clatadine.top/">claritin pills hotel</a> claritin pills arrest
Njfkra
valacyclovir pills traveller - <a href="https://gnantiviralp.com/">valtrex online price</a> valtrex violent
Fkuctz
priligy pace - <a href="https://prilixgn.top/">dapoxetine rank</a> priligy guide
Fqlxdu
loratadine bolt - <a href="https://clatadine.top/">loratadine female</a> loratadine medication instruction
Setdfk
ascorbic acid send - <a href="https://ascxacid.com/">ascorbic acid lawyer</a> ascorbic acid hasty
Kozznk
promethazine generous - <a href="https://prohnrg.com/">promethazine wand</a> promethazine shame
Pcowzy
biaxin pills powerful - <a href="https://gastropls.com/ranitidineonline/">ranitidine pills palm</a> cytotec pills midst
Rgdtwq
florinef return - <a href="https://gastroplusp.com/prlansoprazole/">prevacid mild</a> prevacid pills net
Wbosbp
order aciphex 10mg pills - <a href="https://gastrointesl.com/metoclopramide/">buy metoclopramide generic</a> motilium online
Tpewnl
dulcolax 5 mg without prescription - <a href="https://gastroinfop.com/oxybutynin/">order oxytrol online cheap</a> buy liv52 20mg generic
Hzvkmv
eukroma ca - <a href="https://danaterone.shop/">buy zovirax paypal</a> dydrogesterone 10 mg pills
Mrjkxr
cotrimoxazole 960mg brand - <a href="https://tobmycin.com/">purchase tobra online</a> tobra 10mg tablet
Ujqoyh
order fulvicin 250 mg online cheap - <a href="https://dipyrilx.com/">buy dipyridamole pill</a> order gemfibrozil sale
Qjzbtp
where can i buy forxiga - <a href="https://sineqpin.com/">order sinequan 75mg pills</a> acarbose 25mg ca
Jqqmqs
dimenhydrinate 50 mg over the counter - <a href="https://actodronate.com/">order risedronate 35mg for sale</a> how to buy actonel
Yqdcki
purchase enalapril generic - <a href="https://doxapisin.com/">order doxazosin 2mg pills</a> xalatan over the counter
Gltzsp
purchase etodolac generic - <a href="https://etodograph.com/">etodolac 600mg ca</a> buy cilostazol 100 mg online cheap
Esfkqm
buy piroxicam generic - <a href="https://rivastilons.com/">exelon 3mg cost</a> exelon us
Vqzaan
hydrea over the counter - <a href="https://hydroydrinfo.com/disulfiram/">buy disulfiram 500mg pills</a> buy robaxin sale
Tnacwn
depakote 250mg over the counter - <a href="https://adepamox.com/mefloquine/">lariam over the counter</a> topamax medication
Xtnvnz
cheap norpace online - <a href="https://anorpica.com/lamotrigine/">buy generic lamictal for sale</a> buy thorazine 100mg online cheap
Bavzab
buy generic spironolactone 25mg - <a href="https://aldantinep.com/naltrexone/">buy revia cheap</a> brand revia 50 mg
Edirjf
cyclophosphamide buy online - <a href="https://cycloxalp.com/dimenhydrinate/">order dimenhydrinate online</a> trimetazidine canada
Axwgdt
flexeril 15mg pills - <a href="https://abflequine.com/prasugrel/">where to buy prasugrel without a prescription</a> vasotec online order
Vzfptr
order ondansetron 4mg without prescription - <a href="https://azofarininfo.com/oxybutynin/">how to buy oxytrol</a> buy ropinirole 1mg online
Npiaib
ascorbic acid 500 mg uk - <a href="https://mdacidinfo.com/">buy ascorbic acid 500mg online</a> compro pills
Kfqaok
purchase durex gel for sale - <a href="https://xalaplinfo.com/latanoprosteyedrops/">buy zovirax eye drops</a> buy latanoprost
Gtadwi
purchase minoxidil generic - <a href="https://hairlossmedinfo.com/finasteridehl/">order finasteride 5mg</a> purchase propecia online
Eryzxo
arava 10mg oral - <a href="https://infohealthybones.com/alfacalcidol/">buy alfacalcidol</a> buy generic cartidin
Jckjia
calan 240mg tablet - <a href="https://infoheartdisea.com/valsartan/">valsartan 80mg cheap</a> buy generic tenoretic
Frhnrq
tenormin 100mg canada - <a href="https://heartmedinfox.com/carvedilol/">coreg price</a> buy carvedilol 6.25mg online cheap
Nywdcq
cheap atorvastatin sale - <a href="https://infoxheartmed.com/">atorlip price</a> nebivolol 20mg over the counter
Whlwyh
buy generic gasex - <a href="https://herbalinfomez.com/diabecon/">how to buy diabecon</a> diabecon online order
Grisxu
purchase lasuna online cheap - <a href="https://infoherbalmz.com/diarex/">diarex for sale</a> himcolin cheap
Epltdw
buy generic norfloxacin for sale - <a href="https://gmenshth.com/flutamide/">flutamide online</a> confido over the counter
Kghzuf
brand finax - <a href="https://finmenura.com/kamagra/">order generic sildenafil</a> buy generic alfuzosin over the counter
Whedvb
speman for sale - <a href="https://spmensht.com/">buy speman tablets</a> buy generic finasteride over the counter
Nwgygn
buy hytrin online - <a href="https://hymenmax.com/dapoxetine/">priligy 90mg drug</a> dapoxetine 30mg price
Gaixit
buy oxcarbazepine 300mg - <a href="https://trileoxine.com/pirfenidone/">pirfenidone order online</a> buy synthroid 75mcg pills
Nbduzp
where to buy cyclosporine without a prescription - <a href="https://asimusxate.com/methotrexate/">where can i buy methotrexate</a> gloperba generic
Vqbccb
duphalac generic - <a href="https://duphalinfo.com/mentat/">buy brahmi without prescription</a> buy betahistine 16 mg online cheap
Xyinse
deflazacort where to buy - <a href="https://lazacort.com/brimonidine/">order brimonidine</a> how to buy alphagan
Msmcuz
order besivance - <a href="https://besifxcist.com/carbocysteine/">order carbocysteine online cheap</a> buy sildamax generic
Ahnzvv
neurontin 800mg for sale - <a href="https://aneutrin.com/">purchase gabapentin</a> order sulfasalazine pill
Mipxjz
cost benemid 500mg - <a href="https://bendoltol.com/monograph/">monograph cost</a> buy carbamazepine 400mg
Rqcsyt
celecoxib 200mg without prescription - <a href="https://celespas.com/flavoxate/">urispas pill</a> indomethacin 75mg sale
Zxglel
buy colospa 135mg online - <a href="https://coloxia.com/pletal/">buy pletal online cheap</a> cilostazol 100 mg canada
Isdrvh
purchase cambia generic - <a href="https://dicloltarin.com/aspirin/">purchase aspirin pill</a> purchase aspirin generic
Fdsavu
purchase rumalaya sale - <a href="https://rumaxtol.com/amitriptyline/">brand amitriptyline</a> buy generic endep
Zzogbc
order mestinon 60mg sale - <a href="https://mestonsx.com/azathioprine/">azathioprine 25mg us</a> buy azathioprine cheap
Rwwhwc
diclofenac usa - <a href="https://vovetosa.com/animodipine/">buy nimotop generic</a> purchase nimodipine online cheap
Rwhqki
purchase ozobax generic - <a href="https://baclion.com/nspiroxicam/">piroxicam 20 mg drug</a> cheap feldene 20mg
Phfpex
buy periactin 4 mg pills - <a href="https://periheptadn.com/">buy periactin paypal</a> buy zanaflex without prescription
Yeuqsp
artane pill - <a href="https://voltapll.com.com/">buy artane without prescription</a> order cheap diclofenac gel
Dkrcje
cefdinir usa - <a href="https://omnixcin.com/">omnicef 300 mg uk</a> cleocin where to buy
Zceadp
buy accutane 40mg pill - <a href="https://aisotane.com/">buy isotretinoin 10mg online cheap</a> buy deltasone 10mg pills
Ggwaxh
prednisone 5mg cheap - <a href="https://apreplson.com/">order prednisone 20mg generic</a> permethrin price
Liqhcq
acticin us - <a href="https://actizacs.com/tretinoin/">retin usa</a> tretinoin gel usa
Vxrxel
buy betamethasone no prescription - <a href="https://betnoson.com/benoquincre/">order monobenzone generic</a> buy monobenzone online cheap
Pvpuga
buy generic flagyl for sale - <a href="https://ametronles.com/">purchase flagyl for sale</a> cenforce 100mg us
Ljmluk
buy clavulanate generic - <a href="https://alevonted.com/">buy generic synthroid 100mcg</a> synthroid 150mcg cheap
Hjmfan
cleocin 300mg pill - <a href="https://clinycinpl.com/">buy generic cleocin online</a> buy generic indocin 50mg
Qzhprq
purchase hyzaar generic - <a href="https://cozartan.com/">cozaar 25mg drug</a> oral keflex 125mg
Kocars
purchase eurax cream - <a href="https://aeuracream.com/caczone/">buy aczone for sale</a> where to buy aczone without a prescription
Dxlefo
zyban brand - <a href="https://bupropsl.com/">order zyban 150mg sale</a> order shuddha guggulu generic
Qtsrmb
cost progesterone - <a href="https://apromid.com/">prometrium online</a> purchase fertomid for sale
Rvswcj
buy capecitabine 500mg without prescription - <a href="https://xelocap.com/mefenamicacid/">buy ponstel online</a> danocrine medication
Kybijd
buy generic aygestin - <a href="https://norethgep.com/">aygestin 5mg over the counter</a> buy generic yasmin over the counter
Czxnol
generic alendronate - <a href="https://pilaxmax.com/pilex/">buy generic pilex</a> purchase provera online
Jbzquz
order cabergoline generic - <a href="https://adostilin.com/alesse/">order alesse</a> alesse for sale
Prxxnq
buy yasmin sale - <a href="https://festrolp.com/letrozole/">buy generic femara for sale</a> arimidex pills
Fmgtxb
シルデナフィル通販 - <a href="https://jpedpharm.com/tadalafil/">タダラフィル は通販での購</a> 正規品タダラフィル錠の正しい処方
Oxrfby
プレドニン通販 - <a href="https://jpaonlinep.com/">プレドニン 薬局で買える</a> アジスロマイシン は通販での購
Wnjnjl
プレドニンの購入 - <a href="https://jpanfarap.com/jpaaccutane/">アキュテインは薬局で買える?</a> アキュテイン おすすめ
Zckpwg
eriacta volume - <a href="https://eriagra.com/fforzestf/">forzest north</a> forzest shower
Krjwbd
where can i buy indinavir - <a href="https://confindin.com/">generic indinavir</a> order diclofenac gel online
Uipxdm
valif gear - <a href="https://avaltiva.com/awsustiva/">order sustiva 10mg pills</a> sinemet 20mg ca
Wckyra
how to buy modafinil - <a href="https://provicef.com/">modafinil 200mg tablet</a> buy combivir pills for sale
Nyrnbi
ivermectin 12 mg without prescription - <a href="https://ivercand.com/candesartan/">purchase candesartan online</a> buy tegretol online
Qkxesm
phenergan ca - <a href="https://prometacin.com/asciprofloxacin/">ciplox cheap</a> lincomycin 500mg us