layui自定义表单校验

自定义一个金额的校验


<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">
    
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>

<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>

你可能感兴趣的:(layui)