自定義vue必填驗證指令


 當focus時提示的文字組件可以改成alert

調用方法:

v-required="{
model:obj,attr:'userName'
,msg:'用戶姓名為必填項'
,ref:'userName'
,callback:'backFunName'
,requiredfun:'funName'
,requiredfunPar:item
,valType:'number'
,valMin:0
,valMax:100}"

//vue指定取值 用的
var _VUECOMMON = {
    getValue:function($this,json,attrName){
        let r="";
        if(json && attrName) {
            r = json[attrName];
        }else{
            //因為取vue Data第一級的數據,獲取不到,只能用這樣的方式來取
            r=$this[attrName];
        }
        return r;
    },
    setValue:function(vnode,json,attrName,val){
        if(json && attrName){
            json[attrName] = val;
        }else{
            //因為取vue Data第一級的數據,獲取不到,只能用這樣的方式來取
            $this[attrName] = val;
        }
    },
}
//====================================vue必填驗證指令開始====================================2020-10-21
!function ($vue) {
//驗證指令使用說明(這個指令一定要放在vue.warning后面,因該指令用到了vue.warning來提示)
//最簡單的引用:v-required="{model:obj,attr:'userName'}"
//最推薦的引用:v-required="{model:obj,attr:'userName',field:'用戶名'}"
//自定義組件引用:v-required="{model:obj,attr:'userName',field:'用戶名',ref:'refId'}"
//最全參數引用:v-required="{model:obj,attr:'userName',msg:'用戶姓名為必填項',ref:'userName',callback:'backFunName',requiredfun:'funName',requiredfunPar:item,valType:'number',valMin:0,valMax:100}"
//調用驗證方法:if(this.checkRequired(this)){//驗證通過可以進行保存}
//參數說明
// model:obj,//Data中的Model變量名,如果直接Data第一級可以不帶該參數
// attr:'userName',//Model變量的屬性名,(必填參數)
// field:'User Name',//focus時提示的字段名稱
// msg:'custom msg ',//focus時自定義提示的文字,(當指定了該參數,field無效)
// ref:'refIdName',//當自定義組件時,指定了Ref時使用,如輸入提示組件<multiselect ref="refIdName">
// callback:'backFunName',//當得到焦點focus()以后調用該方法
// requiredfun:'funName',//必填條件判斷方法,該方法必須返回Boolean值,當得條件滿足才進行必填驗證,否則跳過
// requiredfunPar:'funName',//必填條件判斷方法的參數,
// valType:'number',//驗證數據類型,int整數,intN:正整數,number:數字,numberN:正數字
// valMin:0,    //驗證數據類型為數字時,最小值
// valMax:100,  //驗證數據類型為數字時最大值
    $vue.directive('required', {
        bind: function (el, binding, vnode) {
            //console.log("===============================================bind")
            //所有需要必填的全放在Vue.prototype._requiredList
            if (Vue.prototype._requiredList) {
                Vue.prototype._requiredList.push({"el": el, "binding": binding, "vnode": vnode})
            } else {
                Vue.prototype._requiredList = [{"el": el, "binding": binding, "vnode": vnode}];
            }
        },
        update:function(el, binding, vnode){
            //console.log("===============================================update")
            if (Vue.prototype._requiredList) {
                var arr=Vue.prototype._requiredList;
                for (let i in arr) {
                    var item = arr[i];
                    if(item.el==el){
                        //因為數據修改以后整個model數據發生改變了,所以需要修改_requiredList中的值
                        item.binding=binding;
                        item.vnode=vnode;
                    }
                }
            }
        }
    });
    Vue.prototype.checkRequired = function ($this) {
        // console.log($this._requiredList)
        let arr = $this._requiredList;//從Vue.prototype._requiredList中取出必填驗證的對象
        for (let i in arr) {
            var item = arr[i];
            var option = item.binding.value || {};//參數
            // console.log("===============================================")
            // console.log(option)
            var modelValue = _VUECOMMON.getValue($this, option.model, option.attr);//得到值
            //console.log("modelValue:"+modelValue)
            var isRequired = true;//是否需要必填判定
            if (option.requiredfun && typeof (option.requiredfun) == "function") {
                //驗證條件的方法
                //console.log("======requiredfun====")
                isRequired =option.requiredfun(option.requiredfunPar);
            }

            //跳轉到focus的對象
            var toFocus=function(msg){
                var focusDom=null;
                if (option.ref) {
                    if($this.$refs[option.ref].$el){//vue組件 (對象,非數組格式)
                        focusDom=$this.$refs[option.ref].$el;
                    }else if ($this.$refs[option.ref][0]) {//vue組件 (數組格式)
                        focusDom=$this.$refs[option.ref][0].$el;
                    }else{
                        focusDom=$this.$refs[option.ref];//非組件 (普通的DOM元素)
                    }
                } else {
                    focusDom=item.el;//非組件 (普通的DOM元素)
                }
                if(focusDom.offsetParent && !focusDom.disabled && !focusDom.readOnly){
                    //$this.warning(msg);
            alert(msg);//可以改成你的輸入提示組件方法 focusDom.focus();
//回調函數 if (typeof (option.callback) === 'function') { option.callback(item.el, item.binding,item.vnode); } return true;//onfocus成功 }else{ //如果dom display:none or disabled or readOnly,不進行focus; console.log("[v-required warning]this dom display:none or disabled or readOnly,can't focus:"); console.log(focusDom); return false;//onfocus失敗 } } //null 或 '‘ 或 [] 或 {} 都能驗證為空 if (isRequired && (null==modelValue || ''==modelValue || '[]'==JSON.stringify(modelValue) || '{}'==JSON.stringify(modelValue))) { var showMsg=""; if (option.msg) { showMsg=option.msg; } else if (option.field) { showMsg=option.field + ' is required'; } else { showMsg='This is required'; } if(toFocus(showMsg)){return false;} } //數據類型驗證開始 if(modelValue != null && modelValue != '' && option.valType){ var isFocus=false; var showMsg=""; if(option.valType=="int"){//如果不是整數 if(parseInt(modelValue).toString() == "NaN" || parseInt(modelValue)!=modelValue){ isFocus=true; showMsg=(option.field || 'this') + ' is integer!'; } }else if(option.valType=="intN"){//如果不是正整數 if(parseInt(modelValue).toString() == "NaN" || parseInt(modelValue)!=modelValue || modelValue<0){ isFocus=true; showMsg=(option.field || 'this') + ' is positive integer!'; } }else if(option.valType=="number"){//如果不是數字 if(parseFloat(modelValue).toString() == "NaN"){ isFocus=true; showMsg=(option.field || 'this') + ' is number!'; } }else if(option.valType=="numberN"){//如果不是正數字 if(parseFloat(modelValue).toString() == "NaN" || modelValue<0){ isFocus=true; showMsg=(option.field || 'this') + ' is positive number!'; } } if(!isFocus && (option.valMin || option.valMax)){ //如果小於指定的最小值 if(option.valMin && parseFloat(modelValue).toString() != "NaN" && modelValue<option.valMin) { isFocus = true; msg = (option.field || 'this') + ' Must be greater than '+option.valMin+' !'; } //如果大於指定的最大值 if(option.valMax && parseFloat(modelValue).toString() != "NaN" && modelValue>option.valMax) { isFocus = true; msg = (option.field || 'this') + ' Must be less than '+option.valMax+' !'; } } if(isFocus) { if(toFocus(showMsg)){return false;} } } } return true;//如果驗證全通過返回true } }(Vue); //====================================vue必填驗證指令結束====================================


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM