Vue指令实现输入框校验

import Vue from 'vue';

function checkRule(placeholder, value, verifyType, $vm) {
    if (placeholder.startsWith('请输入')) {
        placeholder = placeholder.substr(3);
    } else {
        placeholder = '内容';
    }

    if (value === '' && verifyType === null) {
        $vm.$toast.fail(`${placeholder}不能为空`);
        return false;
    }

    switch (verifyType) {
        case 'ip':
            if (!$vm.$utils.verifyIp(value)) {
                $vm.$toast.fail('ip填写不正确');
                return false;
            }
            break;
    }
}

let bindClass = '';

Vue.directive('auto-switch', {
    bind(el, binding) {
        if (binding.value.class) {
            el.classList.add(`v-check-${binding.value.class}-list`);
            bindClass = `v-check-${binding.value.class}-list`;
            return bindClass;
        }
    },
    inserted(el, binding) {
        let autoFocus = 0;

        if (binding.value.index) {
            autoFocus = binding.value.index;
        }

        let inputArray = el.querySelectorAll('.van-field__control');
        inputArray[autoFocus].focus();

        for (let i = 0; i < inputArray.length; i++) {
            inputArray[i].setAttribute('focusIndex', i);
            inputArray[i].addEventListener('keyup', event => {
                if (event.keyCode === 13) {
                    let verifyType = event.target.getAttribute('verifyType'),
                        attrIndex = Number(event.target.getAttribute('focusIndex')),
                        $vm = window.vm.__proto__,
                        { placeholder, value } = event.target;

                    if (binding.value.verify) {
                        if (checkRule(placeholder, value, verifyType, $vm) === false) {
                            return false;
                        }
                    }

                    if (attrIndex < inputArray.length - 1) {
                        inputArray[attrIndex + 1].focus();
                    }
                }
            });
        }
    }
});

Vue.directive('check-submit', {
    inserted(el, binding) {
        el.addEventListener('click', () => {
            let inputArray = document.querySelectorAll(`.${bindClass} .van-field__control`);

            for (let i = 0; i < inputArray.length; i++) {
                let verifyType = inputArray[i].getAttribute('verifyType'),
                    $vm = window.vm.__proto__,
                    { placeholder, value } = inputArray[i];

                if (checkRule(placeholder, value, verifyType, $vm) === false) {
                    return false;
                }
            }

            let submit = binding.value.fn;
            submit();
        });
    }
});
    原文作者:time23
    原文地址: https://segmentfault.com/a/1190000020114330
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞