layui自定义表单校验

自定义一个金额的校验

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义验证</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../js/layui/css/layui.css" media="all">
    <!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>


<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>自定义验证</legend>
</fieldset>

<form class="layui-form" action="">

    <div class="layui-form-item">
        <label class="layui-form-label">金额</label>
        <div class="layui-input-inline">
            <input type="number" name="myMoney" lay-verify="require|validateMoney" placeholder="请输入金额"
                   autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">请填写最多两位小数的金额</div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<script src="../js/layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
                , layer = layui.layer

        //自定义验证规则
        form.verify({
            validateMoney: function (value) {
                var result = validateMoney(value);
                if (result != "Y") {
                    return result;
                }
            }
        });

        //监听提交
        form.on('submit(demo1)', function (data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });

    /**
     * 金额校验
     * @param money
     * @returns {*}
     */
    function validateMoney(money) {
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (reg.test(money)) {
            return "Y";
        }
        return "请输入正确的金额,且最多两位小数!";
    }
</script>

</body>
</html>
阅读更多

没有更多推荐了,返回首页