欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Layui手动验证表单必填项

程序员文章站 2022-07-15 16:18:40
...

1.JS文件(formVerify.js)

//验证规则设定
var verifyConfig = {
    required: [
        /[\S]+/
        ,'必填项不能为空'
    ]
    ,phone: [
        /^1\d{10}$/
        ,'请输入正确的手机号'
    ]
    ,email: [
        /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
        ,'邮箱格式不正确'
    ]
    ,url: [
        /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
        ,'链接格式不正确'
    ]
    ,number: function(value){
        if(!value || isNaN(value)) return '只能填写数字'
    }
    ,date: [
        /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/
        ,'日期格式不正确'
    ]
    ,identity: [
        /(^\d{15}$)|(^\d{17}(x|X|\d)$)/
        ,'请输入正确的身份证号'
    ]
};
//扩展JQuery
$.fn.formVerify=function(v){
    var device = layui.device();

    var stop = null //验证不通过状态
        ,verify = verifyConfig //验证规则
        ,DANGER = 'layui-form-danger' //警示样式
        ,verifyElem = this.find('*[lay-verify]'); //获取需要校验的元素

    //开始校验
    layui.each(verifyElem, function(_, item){
        var othis = $(this)
            ,vers = othis.attr('lay-verify').split('|')
            ,verType = othis.attr('lay-verType') //提示方式
            ,value = othis.val();

        othis.removeClass(DANGER); //移除警示样式

        //遍历元素绑定的验证规则
        layui.each(vers, function(_, thisVer){
            var errorText = '' //错误提示文本
                ,isFn = typeof verify[thisVer] === 'function';

            //匹配验证规则
            if(verify[thisVer]){
                var isTrue = isFn ? errorText = verify[thisVer](value, item) : !verify[thisVer][0].test(value);
                errorText = errorText || verify[thisVer][1];

                if(thisVer === 'required'){
                    errorText = othis.attr('lay-reqText') || errorText;
                }

                var verifyType=$(item).attr('type');
                if(verifyType==="radio" || verifyType==="checkbox"){
                    var verifyName=$(item).attr('name')
                        ,verifyElem=$(item).parents('.layui-form').find('input[name='+verifyName+']');
                    isTrue= !verifyElem.is(':checked');
                    if(isTrue){
                        var focusElem = verifyElem.next().find('i.layui-icon');
                        //定位焦点
                        focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                        //对非输入框设置焦点
                        focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                            focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                        }).focus();

                        if(verType === 'tips'){
                            layer.tips(errorText, function(){
                                return othis.next();
                            }(), {tips: 1});
                        } else if(verType === 'alert'){
                            layer.alert(errorText, {title: '提示', shadeClose: true});
                        } else {
                            layer.msg(errorText, {icon: 5, shift: 6});
                        }
                        return stop = true;
                    }
                }

                //如果是必填项或者非空命中校验,则阻止提交,弹出提示
                if(isTrue){
                    //提示层风格
                    if(verType === 'tips'){
                        layer.tips(errorText, function(){
                            if(typeof othis.attr('lay-ignore') !== 'string'){
                                if(item.tagName.toLowerCase() === 'select' || /^checkbox|radio$/.test(item.type)){
                                    return othis.next();
                                }
                            }
                            return othis;
                        }(), {tips: 1});
                    } else if(verType === 'alert') {
                        layer.alert(errorText, {title: '提示', shadeClose: true});
                    } else {
                        layer.msg(errorText, {icon: 5, shift: 6});
                    }

                    //非移动设备自动定位焦点
                    if(!device.android && !device.ios){
                        setTimeout(function(){
                            item.focus();
                        }, 7);
                    }

                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if(stop) return stop;
    });
    if(stop){
        return false;
    } else {
        return true;
    }
};

//直接定义JS方法
function formVerify(formId){
    var $ = layui.$
        //,layer = layui.layer
        ,device = layui.device();

    var stop = null //验证不通过状态
        ,verify = verifyConfig //验证规则
        ,DANGER = 'layui-form-danger' //警示样式
        ,verifyElem = $(formId).find('*[lay-verify]'); //获取需要校验的元素

    //开始校验
    layui.each(verifyElem, function(_, item){
        var othis = $(this)
            ,vers = othis.attr('lay-verify').split('|')
            ,verType = othis.attr('lay-verType') //提示方式
            ,value = othis.val();

        othis.removeClass(DANGER); //移除警示样式

        //遍历元素绑定的验证规则
        layui.each(vers, function(_, thisVer){
            var errorText = '' //错误提示文本
                ,isFn = typeof verify[thisVer] === 'function';

            //匹配验证规则
            if(verify[thisVer]){
                var isTrue = isFn ? errorText = verify[thisVer](value, item) : !verify[thisVer][0].test(value);
                errorText = errorText || verify[thisVer][1];

                if(thisVer === 'required'){
                    errorText = othis.attr('lay-reqText') || errorText;
                }

                var verifyType=$(item).attr('type');
                if(verifyType==="radio" || verifyType==="checkbox"){
                    var verifyName=$(item).attr('name')
                        ,verifyElem=$(item).parents('.layui-form').find('input[name='+verifyName+']');
                    isTrue= !verifyElem.is(':checked');
                    if(isTrue){
                        var focusElem = verifyElem.next().find('i.layui-icon');
                        //定位焦点
                        focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                        //对非输入框设置焦点
                        focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                            focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                        }).focus();

                        if(verType === 'tips'){
                            layer.tips(errorText, function(){
                                return othis.next();
                            }(), {tips: 1});
                        } else if(verType === 'alert'){
                            layer.alert(errorText, {title: '提示', shadeClose: true});
                        } else {
                            layer.msg(errorText, {icon: 5, shift: 6});
                        }
                        return stop = true;
                    }
                }

                //如果是必填项或者非空命中校验,则阻止提交,弹出提示
                if(isTrue){
                    //提示层风格
                    if(verType === 'tips'){
                        layer.tips(errorText, function(){
                            if(typeof othis.attr('lay-ignore') !== 'string'){
                                if(item.tagName.toLowerCase() === 'select' || /^checkbox|radio$/.test(item.type)){
                                    return othis.next();
                                }
                            }
                            return othis;
                        }(), {tips: 1});
                    } else if(verType === 'alert') {
                        layer.alert(errorText, {title: '提示', shadeClose: true});
                    } else {
                        layer.msg(errorText, {icon: 5, shift: 6});
                    }

                    //非移动设备自动定位焦点
                    if(!device.android && !device.ios){
                        setTimeout(function(){
                            item.focus();
                        }, 7);
                    }

                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if(stop) return stop;
    });
    if(stop){
        return false;
    } else {
        return true;
    }
};

2.调用验证方法

<form id="addUserForm" class="layui-form layui-form-pane">
     <div class="layui-form-item">
         <label class="layui-form-label">登录账号</label>
         <div class="layui-input-block">
             <input type="text" name="userName" class="layui-input" lay-verify="required">
         </div>
     </div>
     <div class="layui-form-item">
         <label class="layui-form-label">登录密码</label>
         <div class="layui-input-block">
             <input type="password" name="passWord" class="layui-input" lay-verify="required|pass">
         </div>
     </div>
</form>

<a class="layui-btn" onclick="formSubmit()">提交表单</a>

<script src="formVerify.js" type="text/javascript"></script>
<script>
//自定义验证规则
layui.$.extend(true, verifyConfig,
     {
         pass: [
             /^[\S]{6,12}$/
             ,'密码必须6到12位,且不能出现空格'
         ]
     }
);

function formSubmit(){
    if($("#addUserForm").formVerify()){
        alert("表单提交成功");
    }
}
</script>