使用lay-verify有兩個須要注意的地方:javascript
class="layui-form"
lay-submit=""
如:java
<form action="#" method="post" class="layui-form"> <input id="login-username" type="text" name="username" placeholder="Username" lay-verify="required|username"> <input id="login-password" type="password" name="password" placeholder="Password" lay-verify="required|password"> <input class="layui-btn layui-btn-fluid layui-btn-normal " lay-submit="" type="button" value="Login" lay-filter="login-submit"> </form>
JS部分:ajax
<script type="text/javascript"> layui.use(['layer', 'form'], function () { var layer = layui.layer; var form = layui.form; form.verify({ username: function (value, item) { //value:表單的值、item:表單的DOM對象 if (!new RegExp("^(.+){4,18}$").test(value)) { return '用戶名長度必須爲4-18位' } if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) { return '用戶名不能有特殊字符'; } if (/(^\_)|(\__)|(\_+$)/.test(value)) { return '用戶名首尾不能出現下劃線\'_\''; } if (/^\d+\d+\d$/.test(value)) { return '用戶名不能全爲數字'; } }, password: [ /^[\S]{6,18}$/, '密碼必須6到12位,且不能出現空格' ], confirm_password: function (value) { if (!new RegExp("^[\\S]{6,18}$").test(value)) { return '密碼長度必須爲6-18位' } if (value !== $('#login-password').val()) { return '兩次輸入的密碼不一致'; } } }); form.on('submit(login-submit)', function (data) { var login_username = $("#login-username"); var login_password = $("#login-password"); var username = login_username.val(); var password = login_password.val(); password = md5(password); $.ajax({ url: "/XXX/login/", type: "POST", data: { username: username, password: password, csrfmiddlewaretoken: '{{ csrf_token }}' }, async: false, success: function (data) { var status = data.status; if (status === 0) { $("#myModal").modal('hide'); layer.msg("Login Success!", {offset: '200px'}); // todo something after login } else if (status === 21) { // user not exist layer.msg(data.msg, {offset: '200px'}); login_username.val(""); login_password.val(""); login_username.focus(); } else if (status === 22) { // wrong password layer.msg(data.msg, {offset: '200px'}); login_password.val(""); login_password.focus(); } else { layer.msg(data.msg, {offset: '200px'}); } }, error: function () { layer.msg("System Service Busy!", {offset: '200px'}); } }); return false; }); }); </script>