jQuery Validate是否有类似CodeIgniter 4中is_unique的验证方法?
jQuery Validate实现类似CodeIgniter 4的is_unique唯一性验证
jQuery Validate没有内置对应CodeIgniter 4中is_unique的验证规则,要实现字段唯一性验证,需要借助它提供的remote规则,通过AJAX请求后端接口完成数据库的唯一性校验。
1. 前端修改jQuery Validate配置
将原来自定义的is_unique规则替换为remote规则,配置后端校验接口的地址、请求方式及传递参数:
<script> $(document).ready(function() { if ($('.formsave').length > 0) { $('.formsave').validate({ rules: { catcode: { required: true, // 使用remote规则对接后端校验接口 remote: { url: '/your-controller/valid-unique-catcode', // 替换为你的控制器方法地址 type: 'post', data: { // 传递当前输入的catcode值 catcode: function() { return $('#catcode').val(); }, // 若为编辑场景,需传递当前记录ID以排除自身校验 // id: function() { // return $('#category_id').val(); // } } } }, catname: { required: true, // catname的唯一性校验同理 remote: { url: '/your-controller/valid-unique-catname', type: 'post', data: { catname: function() { return $('#catname').val(); } } } }, catstatus: { required: true } }, messages: { catcode: { required: "Please enter category code such as F & B", remote: "Sorry, category code already taken, please choose another code for this category!" }, catname: { required: "Please enter category name such as Food & Beverage", remote: "Sorry, category name already taken, please choose another name!" }, catstatus: { required: "Please select Enable or Disable for the category You created" } } }); } }); </script>
2. 后端CodeIgniter 4控制器实现校验接口
创建对应的控制器方法,接收前端参数后查询数据库,返回校验结果(jQuery Validate要求后端返回"true"字符串表示校验通过,返回错误文本或"false"表示不通过):
// 校验catcode唯一性的方法 public function validUniqueCatcode() { $catcode = $this->request->getPost('catcode'); // 编辑场景下获取当前记录ID // $id = $this->request->getPost('id'); // 实例化模型(替换为你的实际模型类) $catModel = new \App\Models\TbcatModel(); $query = $catModel->where('cat_code', $catcode); // 编辑时排除当前记录,避免自身重复校验 // if (!empty($id)) { // $query->where('id !=', $id); // } // 查询是否存在重复记录 $exists = $query->first(); if ($exists) { // 存在重复,返回错误提示 echo json_encode("Sorry, category code already taken, please choose another code for this category!"); } else { // 无重复,返回true表示校验通过 echo json_encode(true); } } // 校验catname唯一性的方法 public function validUniqueCatname() { $catname = $this->request->getPost('catname'); // $id = $this->request->getPost('id'); $catModel = new \App\Models\TbcatModel(); $query = $catModel->where('cat_name', $catname); // if (!empty($id)) { // $query->where('id !=', $id); // } $exists = $query->first(); if ($exists) { echo json_encode("Sorry, category name already taken, please choose another name!"); } else { echo json_encode(true); } }
注意事项
- 确保后端接口的路由配置正确,前端
remote的url能正确访问到控制器方法 - 编辑场景下必须传递当前记录ID,否则会把自身记录判定为重复
- 后端返回的内容必须是JSON格式的字符串,jQuery Validate才能正确解析
内容的提问来源于stack exchange,提问作者me.theblackz
相关产品推荐
相关产品推荐

