form表单验证对表中数据的校验

form表单验证时对表中数据的校验

在做项目时,被要求当添加表时,要对非主键的编号进行校验,当为空时,提示空值;非空但与数据库重复时,提示已存在。


使用rules和message

在form.validate中,提交时,我们用到submitHandle,在对数据添加规则时,要使用rules,看代码:
$(document).ready(function() {
            validateForm = $("#inputForm").validate({
                rules:{
                    podButtonNo:{
                        required: true,
                        remote: {
                            url: "/jeeplus/a/produce/lyPodButton/isPodButtonLssued",
                            type: "post",
                            data: {
                                podButtonNo: function() {
                                    return $("#podButtonNo").val();
                                }
                            }

                        }
                    }

                },

                 messages: {
                     podButtonNo: {
                            required: "请输按钮编号",
                            remote:"按钮编号已存在"
                        }               
                    },
                submitHandler: function(form){
                    loading('正在提交,请稍等...');
                    form.submit();
                },
                errorContainer: "#messageBox",
                errorPlacement: function(error, element) {
                    $("#messageBox").text("输入有误,请先更正。");
                    if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

        });

因为我在input标签中id为podButtonNo,其中podButtonNo为实体类的属性;当required:true,这个是对podButtonNo一个限制,要求必须非空;当满足非空之后,就会将input获取来的值,通过异步方式发送给controller层,controller层会接收前端传输过来的数据,并通过数据库获取数据,此时,要进行一次判断,我将获取的数据,存储在list集合中,当list集合为空或者size()<=0时,返回true 表示可以添加;否则返回false。
message: //如果不符合要求时要提示的信息

    @RequestMapping("isPodButtonLssued")
    @ResponseBody
    public boolean isPodButtonLssued(Model model,HttpServletRequest request) {
        LyPodButton lyPodButton = new LyPodButton();
        String podButtonNo = request.getParameter("podButtonNo");
        lyPodButton.setPodButtonNo(podButtonNo);
        List<LyPodButton> list = lyPodButtonService.findListByNo(lyPodButton);
        if(list == null || list.size() <= 0) {
            return true;
        }
        return false;
    }

离线写博客

本人写的博客绝对原创,属于自己在开过过程中,认为容易忽略的小错误将其记录下来,以作为以后给自己的提醒,如果有错误希望可以指出来,大家互相促进,互相学习。
在开发这条不归路上,只有互相分享才能走得长久,互相交换思想,就会获取两个,只是自己思考就会局限在一个思维困境中。

猜你喜欢

转载自blog.csdn.net/weixin_42803027/article/details/81501682