{{-- 表单验证插件--}}
<script src="{{asset('lib/formvalidation/js/formValidation.min.js')}}"></script>
<script src="{{asset('lib/formvalidation/js/framework/bootstrap.min.js')}}"></script>
<script src="{{asset('lib/formvalidation/js/language/zh_CN.js')}}"></script>
<script>
$(".from1").formValidation({
//配置语言
locale: "zh_CN",
//false:其它规则验证通过后再进行远程验证 true:输入后立马验证 ,放这里控制全体
// verbose: false,
//验证字段
fields: {
pid: {
validators: {
notEmpty: true,
}
},
name: {
//单独控制
verbose: false,
validators: {
notEmpty: true,
stringLength:{
min:2,
max:8,
message:"长度为2-8个字符"
},
//异步验证是否已存在
remote: {
type: 'POST',
url: '{{ route("console.categoryIsExist") }}',
data: {
_token: "{{csrf_token()}}"
},
// message: '该分类已存在',
delay: 1000
}
}
}
}
})
</script>
//分类新增处理-异步验证该分类是否存在
public function categoryIsExist(Request $request)
{
//表单验证
$validator = Validator::make($request->all(), [
'name' => ['required', 'min:2', 'max:8']
]);
if ($validator->fails()) {//表单验证不通过
return response()->json(['valid' => false, 'message' => $validator->errors()->first()]);
}
$count = Category::where('name',$request->get('name'))->count();
if($count > 0){
return response()->json(['valid' => false, 'message' => "该分类已经存在"]);
}
return response()->json(['valid' => true]);
}
就是通过前端传递过来是是不是更新,然后把当前数据的id传递过来
//分类新增处理-异步验证该分类是否存在
public function categoryIsExist(Request $request)
{
//表单验证
$validator = Validator::make($request->all(), [
'name' => ['required', 'min:2', 'max:8']
]);
if ($validator->fails()) {//表单验证不通过
return response()->json(['valid' => false, 'message' => $validator->errors()->first()]);
}
//接收数据
$name = $request->get('name');
$method = $request->get('method');
$id = $request->get('id');
//判断数据是否存在是否是更新操作
if ($method == 'update') {
//如果是更新操作就必须传递ID过来,否则返回错误
if ($id == null) {
return response()->json(['valid' => false, 'message' => "参数非法"]);
}
//->where('id', "!=" . $id)->where('name', $name)->get();
//排除更新传递过来的id
$count = auth()->user()->categories()->where('id', "!=" ,$id)->where('name', $name)->count();
} else {
$count = auth()->user()->categories()->where('name', $name)->count();
}
if ($count > 0) {
return response()->json(['valid' => false, 'message' => "该分类已经存在"]);
}
return response()->json(['valid' => true]);
}
<script>
$(".from1").formValidation({
//配置语言
locale: "zh_CN",
//false:其它规则验证通过后再进行远程验证 true:输入后立马验证 ,放这里控制全体
// verbose: false,
//验证字段
fields: {
pid: {
validators: {
notEmpty: true,
}
},
name: {
//单独控制
verbose: false,
validators: {
notEmpty: true,
//异步验证是否已存在
remote: {
type: 'POST',
url: '{{ route("console.categoryIsExist") }}',
data: {
_token: "{{csrf_token()}}",
method: "update",
//把当前的id传递回去,用于排除
id:"{{$category->id}}"
},
// message: '该分类已存在',
delay: 1000
}
}
}
}
})
</script>