js前端表單數(shù)據(jù)處理表單數(shù)據(jù)校驗
前言
這段時間一直在搞to B方向中后臺的項目,表單接觸的頻率會比較多,就突發(fā)奇想聊聊表單數(shù)據(jù)相關(guān)的一些基礎(chǔ)分享
1.數(shù)據(jù)處理
當表單在視圖所展示的數(shù)據(jù)并不是后端需要的數(shù)據(jù),或者后端返回的數(shù)據(jù)不是前端所要展示的內(nèi)容,這時就需要進行數(shù)據(jù)轉(zhuǎn)換,下面介紹幾種常見的場景
我假設(shè)有下面的一組form基礎(chǔ)數(shù)據(jù)
data(){ return { form:{ name: '商品名稱', id: '訂單編號', nickName: '商品別名', num: '商品數(shù)量', price:'價格', tag: '0' // 1 表示特價 0 表示無特價 }, } },
1.1 場景1 :過濾我不要的數(shù)據(jù)
場景:當前端form中的數(shù)據(jù)存在冗余的字段,也就是說后端并不需要這些字段,我們可以通過過濾把不必要的字段篩選掉
const noRequired = ['tag', 'nickName']; //不需要的字段 const formData = Object.keys(this.form) .filter(each => !noRequired.includes(each)) .reduce((acc, key) => (acc[key] = this.form[key], acc), {});
1.2 場景2:只提取我要的數(shù)據(jù)
場景:后端不需要表單數(shù)據(jù)那么多數(shù)據(jù),只需要一部分時可以用
const formData= JSON.parse( JSON.stringify(this.form,["nickName","price"]) );
1.3 場景3 :覆蓋數(shù)據(jù)
場景:當前表單有部分字段需要替換或覆蓋新的數(shù)據(jù)時可用
Object.assign(this.form, { tag: '商品1' }
1.4 場景4 :字段映射
當前表單字段需要映射為其他字段名稱時可用,如下對應(yīng)的name的key值換為Name
- 單個字段映射情況
const formData = JSON.parse( JSON.stringify(this.form).replace( /name/g, 'Name') );
- 多字段映射情況
const mapObj = { name: "Name", nickName: "NickName", tag: "Tag" }; const formData = JSON.parse( JSON.stringify(this.form).replace( /name|nickName|tag/gi, matched => mapObj[matched]) );
ps:這種方式有bug,你知道是什么嗎?
1.5 場景5 : 數(shù)據(jù)映射
當字段存在0,1等狀態(tài)數(shù),需要轉(zhuǎn)換成為相對應(yīng)的表示時可用,如下對應(yīng)的tag字段,0對應(yīng)特價,1對應(yīng)無特價,進行映射轉(zhuǎn)換
const formData = JSON.parse(JSON.stringify(this.form,(key,value)=>{ if(key == 'tag'){ return ['特價','無特價'][value]; } return value; }));
1.6 場景6: 數(shù)據(jù)合并
數(shù)據(jù)合并,將表單數(shù)據(jù)字段合并,注意的是,如果字段相同,會覆蓋前面表單數(shù)據(jù)字段的數(shù)值
const query = { tenaId: '訂單編號', id:'查詢ID'} const formData = { ...this.form, query }
2.表單校驗
當表單數(shù)據(jù)填寫完成,需要進一步做表單提交傳送后端服務(wù)器,但是前端需要做數(shù)據(jù)的進一步確實是否符合規(guī)則,比如是否為必填項、是否為手機號碼格式
2.1 簡單版的單字段檢查
data() { return { schema:{ phone: { required:true }, } }; }, methods: { // 判斷輸入的值 validate(schema, values) { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; }, } console.log(this.validate(schema, {phone:'159195**34'}));
2.2 簡單版的多字段檢查
data() { return { phoneForm: { phoneNumber: '', verificationCode: '', tips:'' }, schema:{ phoneNumber: [{required: true, error: '手機不能為空'}, { regex: /^1[3|4|5|6|7|8][0-9]{9}$/, error: '手機格式不對', }], verificationCode: [{required: true, error: '驗證碼不能為空'}], } }; }, methods: { // 判斷輸入的值 validate(schema, values) { const valArr = schema; for (const field in schema) { if (Object.prototype.hasOwnProperty.call(schema, field)) { for (const key of schema[field]) { if (key.required) { if (!valArr[field]) { valArr.tips = key.error; return false; } } else if (key.regex) { if (!new RegExp(key.regex).test(valArr[field])) { valArr.tips = key.error; return false; } } } } } return true; }, } console.log(this.validate(this.schema, this.phoneForm);
2.3 Iview 組件庫 form表單組件的校驗實現(xiàn)
Iview 的 Form 組件模塊主要由Form 和 FormItem組成
- Form 主要是對form做一層封裝
- FormItem 是一個包裹,主要用來包裝一些表單控件、提示消息、還有校驗規(guī)則等內(nèi)容。
我們可以清晰看到,iview的 form 組件是通過async-validator工具庫來作為表單驗證的方法
- async-validator的基本使用
官方例子如下?? 文檔鏈接
import schema from 'async-validator'; var descriptor = { address: { type: "object", required: true, fields: { street: {type: "string", required: true}, city: {type: "string", required: true}, zip: {type: "string", required: true, len: 8, message: "invalid zip"} } }, name: {type: "string", required: true} } var validator = new schema(descriptor); validator.validate({ address: {} }, (errors, fields) => { // errors for address.street, address.city, address.zip });
而在iview的 form 組件中主要定義了validate函數(shù)中使用 field.validate就是調(diào)用async-validator的方法,用來管理form-item組件下的驗證
// ViewUI/src/components/form/form.vue methods:{ validate(callback) { return new Promise(resolve => { let valid = true; let count = 0; this.fields.forEach(field => { field.validate('', errors => { if (errors) { valid = false; } // 檢驗已完成的校驗的數(shù)量是否完全,則返回數(shù)據(jù)有效 if (++count === this.fields.length) { // all finish resolve(valid); if (typeof callback === 'function') { callback(valid); } } }); }); }); }, //針對單個的校驗 validateField(prop, cb) { const field = this.fields.filter(field => field.prop === prop)[0]; if (!field) {throw new Error('[iView warn]: must call validateField with valid prop string!'); } field.validate('', cb); } //表單規(guī)則重置 resetFields() { this.fields.forEach(field => { field.resetField(); }); }, }, created () { //通過FormItem定義的prop來收集需要校驗的字段, this.$on('on-form-item-add', (field) => { if (field) this.fields.push(field); return false; }); // 移除不需要的字段 this.$on('on-form-item-remove', (field) => { if (field.prop) this.fields.splice(this.fields.indexOf(field), 1); return false; }); }
Form.vue 中涉及到的 this.fields 里面的規(guī)則 是在其create生命周期時通過監(jiān)聽‘on-form-item-add’push進來的,‘on-form-item-add’事件是由form-item 組件 觸發(fā)相對應(yīng)的事件,并傳入相對應(yīng)的實例就可以創(chuàng)建數(shù)據(jù)的關(guān)聯(lián),以下是form-item的生命周期函數(shù)內(nèi)容:
// ViewUI/src/components/form/form-item.vue mounted () { // 如果定義了需要驗證的字段 if (this.prop) { // 向父親Form組件添加field this.dispatch('iForm', 'on-form-item-add', this); Object.defineProperty(this, 'initialValue', { value: this.fieldValue }); this.setRules(); } }, beforeDestroy () { // 移除之前刪除form中的數(shù)據(jù)字段 this.dispatch('iForm', 'on-form-item-remove', this); } methods: { setRules() { //獲取所有規(guī)則 let rules = this.getRules(); if (rules.length&&this.required) { return; }else if (rules.length) { rules.every((rule) => { this.isRequired = rule.required; }); }else if (this.required){ this.isRequired = this.required; } this.$off('on-form-blur', this.onFieldBlur); this.$off('on-form-change', this.onFieldChange); this.$on('on-form-blur', this.onFieldBlur); this.$on('on-form-change', this.onFieldChange); }, getRules () { let formRules = this.form.rules; const selfRules = this.rules; formRules = formRules ? formRules[this.prop] : []; return [].concat(selfRules || formRules || []); }, validate(trigger, callback = function () {}) { let rules = this.getFilteredRule(trigger); if (!rules || rules.length === 0) { if (!this.required) { callback(); return true; }else { rules = [{required: true}]; } } // 設(shè)置AsyncValidator的參數(shù) this.validateState = 'validating'; let descriptor = {}; descriptor[this.prop] = rules; const validator = new AsyncValidator(descriptor); let model = {}; model[this.prop] = this.fieldValue; validator.validate(model, { firstFields: true }, errors => { this.validateState = !errors ? 'success' : 'error'; this.validateMessage = errors ? errors[0].message : ''; callback(this.validateMessage); }); this.validateDisabled = false; }, }
感興趣小伙伴可以在這個基礎(chǔ)上通過源碼的學(xué)習(xí)深入研究iview組件庫的form表單校驗的具體實現(xiàn)。
2.4 element 組件庫 ElForm表單組件的校驗實現(xiàn)
element的ElForm表單組件校驗原理跟上一節(jié)講的iview組件庫很像,這里就不做大篇幅介紹說明,直接“上才藝”-----源碼鏈接
2.5 常見校驗規(guī)則
通過不同正則規(guī)則,來約束不同類型的表單數(shù)據(jù)是否符合要求
是否為手機號碼: /^1[3|4|5|6|7|8][0-9]{9}$/
是否全為數(shù)字: /^[0-9]+$/
是否為郵箱:/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
是否為身份證:/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
是否為Url:/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/
是否為IP: /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/
以上就是js前端表單數(shù)據(jù)處理表單數(shù)據(jù)校驗的詳細內(nèi)容,更多關(guān)于js前端表單數(shù)據(jù)校驗處理的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微信小程序 less文件編譯成wxss文件實現(xiàn)辦法
這篇文章主要介紹了微信小程序 less文件編譯成微信小程序wxss文件實現(xiàn)辦法的相關(guān)資料,這里給出具體實現(xiàn)方法,需要的朋友可以參考下2016-12-12微信小程序 解決請求服務(wù)器手機預(yù)覽請求不到數(shù)據(jù)的方法
這篇文章主要介紹了微信小程序 解決請求服務(wù)器手機預(yù)覽請求不到數(shù)據(jù)的方法的相關(guān)資料,配置https時,要使用443端口,就可以解決,需要的朋友可以參考下2017-01-01JavaScript前端學(xué)算法題解LeetCode最大重復(fù)子字符串
這篇文章主要為大家介紹了JavaScript前端學(xué)算法題解LeetCode最大重復(fù)子字符串,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09mini?webpack打包基礎(chǔ)解決包緩存和環(huán)依賴
這篇文章主要為大家介紹了mini?webpack打包基礎(chǔ)解決包緩存和環(huán)依賴示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09字節(jié)飛書面試promise.all實現(xiàn)示例
這篇文章主要為大家介紹了字節(jié)飛書面試promise.all實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06