<form id="updateForm"> <div class="layui-form-item"> <label class="layui-form-label">标题</label> <div class="layui-input-block"> <input type="text" id="title" name="title" required lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">作者</label> <div class="layui-input-block"> <input type="text" id="author" name="author" required lay-verify="required" placeholder="请输入作者" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">价格</label> <div class="layui-input-block"> <input type="text" id="price" name="price" required lay-verify="required" placeholder="请输入价格" autocomplete="off" class="layui-input"> </div> </div> </form> <script> layui.use(['form'], function(){ var form = layui.form; // 表单验证 form.verify({ title: function(value){ if(value.length > 50){ return '标题不能超过50个字符'; } }, author: function(value){ if(value.length > 20){ return '作者不能超过20个字符'; } }, price: function(value){ if(isNaN(value)){ return '价格必须是数字'; } } }); }); </script>将该代码的<head>和样式等文件补充完整
时间: 2023-06-26 13:05:44 浏览: 231
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>表单验证示例</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css">
</head>
<body>
<div class="layui-container">
<form id="updateForm" class="layui-form" action="" method="post">
<div class="layui-form-item">
<label class="layui-form-label">标题</label>
<div class="layui-input-block">
<input type="text" id="title" name="title" required lay-verify="required|title" placeholder="请输入标题" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">作者</label>
<div class="layui-input-block">
<input type="text" id="author" name="author" required lay-verify="required|author" placeholder="请输入作者" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">价格</label>
<div class="layui-input-block">
<input type="text" id="price" name="price" required lay-verify="required|price" placeholder="请输入价格" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="updateForm">提交</button>
</div>
</div>
</form>
</div>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
<script>
layui.use(['form'], function(){
var form = layui.form;
// 自定义表单验证规则
form.verify({
title: function(value){
if(value.length > 50){
return '标题不能超过50个字符';
}
},
author: function(value){
if(value.length > 20){
return '作者不能超过20个字符';
}
},
price: function(value){
if(isNaN(value)){
return '价格必须是数字';
}
}
});
// 监听表单提交事件
form.on('submit(updateForm)', function(data){
// 在这里进行表单提交的操作
// ...
return false; // 阻止表单跳转
});
});
</script>
</body>
</html>
阅读全文