hplus(h+) jQuery Validate 表单验证

说明

hplus的表单,使用了 jQuery Validate 表单验证

详细用法参见:
https://www.runoob.com/jquery/jquery-plugin-validate.html

使用

官方例子:
https://hplus_admin.gitee.io/hplus/form_validate.html

关键

  • 要有 <form> 标签
  • 要有 type="submit" 的按钮
  • 表单控件要有 name 属性
  • 要有 $("#commentForm").validate()
  • 去掉 <script src="js/demo/form-validate-demo.js"></script>

案例

html:

<form class="form-horizontal m-t" id="commentForm">
    <div class="form-group">
        <label class="col-sm-3 control-label">姓名:</label>
        <div class="col-sm-8">
            <input id="username" name="username" minlength="2" type="text" class="form-control" required="" aria-required="true">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">QQ:</label>
        <div class="col-sm-8">
            <input id="qq" name="qq" minlength="5" type="text" class="form-control" required="" aria-required="true">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">联系方式:</label>
        <div class="col-sm-8">
            <input id="phone" name="phone" minlength="11" maxlength="11" type="text" class="form-control" required="" aria-required="true">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-4 col-sm-offset-3">
            <button class="btn btn-primary" type="submit" id="sbmt">添加</button>
        </div>
    </div>
</form>

JavaScript:

$(document).ready(function () {
    $("#commentForm").validate({
        submitHandler: function(form){ // 校验通过,执行的函数
            const username = $("#username").val()
            const qq = $("#qq").val()
            const phone = $("#phone").val()

            $.ajax({
                url:'/mgr/card/add',//请求的url。在html中的/,表示从域名后面开始
                type:'post', //请求方式,GET或POST
                data:{ //要提交给服务器的数据
                    username, // es6 新写法,支持简写,同名写一个就行
                    qq:qq,
                    phone:phone
                },
                dataType:'json',//服务器返回数据的类型
                success:function(data){//成功时执行该函数,data就是服务器返回的数据
                    if(data.code==0){
                        location.href="list.html"
                    }else{
                        //登录失败
                        $("#msg").html(data.msg)//向id是msg的标签,显示文字
                    }
                },
                error:function(xhr,textStatus){//错误时执行该函数
                    console.log('错误')
                    console.log(xhr)
                    console.log(textStatus)
                }
            })
        }
    });
})

原文出处:https://malaoshi.top/show_1IX6EtcFEHIW.html