2

我正在使用 jquery.validate.js 进行验证以识别重复条目

这是我的自定义方法

jQuery.validator.addMethod("uniqueName", function(name, element) {
    var response;
    $.ajax({
        type: "POST",
        dataType : "json",
        url:"${pageContext.request.contextPath}/company/getDuplicate",
        data:{"name":name},
        async:false,
        success:function(data){
            response = ( data == 'present' ) ? true : false;
        }
    })
     return response; 
}, "Name is Already Taken");

这是我在控制器中的 Spring 方法

@RequestMapping(value = "/company/getDuplicate", method = RequestMethod.POST, headers = "Accept=*/*")
    public @ResponseBody void getTitleList(@RequestParam(value="name") String name,HttpServletRequest request, HttpServletResponse response) {

       JSONObject json = new JSONObject();
       List<Company> matched = companyService.getDuplicate(name);

       System.out.println("Matched =====> "+matched);

       String s = "[]";

       if(s.equals(matched)){
           System.out.println(" Not Present");
           json.put("name", "notPresent");
           System.out.flush();
       }
       else{
           System.out.println("Present");
           json.put("name", "present");
           System.out.flush();
       }
   }

通过这种方法,我能够获取数据是否重复(通过“匹配”变量),如果数据存在于数据库中,则返回相同的数据,如果数据不存在,则返回“[]”(因为我使用了列表类型)

我的问题是:在 if 语句条件错误中,对于所有数据,即使它们没有数据,它也会进入 else 块(即“匹配”变量返回“[]”)。以及如何在自定义验证方法中设置该状态

提前致谢。

4

2 回答 2

2

替换你的ajax方法

$.ajax({
            type: "POST",
            dataType : "json",
            url:"${pageContext.request.contextPath}/company/getDuplicate",
            data:{"name":name},
            async:false,
            success:function(data){
                /* alert(data); */
                response = ( data == true ) ? true : false;
            }
        })
         return response;
    }, "Name is Already Taken");
于 2013-07-30T11:00:48.650 回答
0
 String s = "[]";    
 if(s.equals(matched))

这不是检查列表是否为空的方法,而是使用matched.isEmpty()非空检查。所以你的条件将是

   if(matched!=null && matched.isEmpty()){
       System.out.println(" Not Present");
       json.put("name", "notPresent");
       System.out.flush();
   }
   else{
       System.out.println("Present");
       json.put("name", "present");
       System.out.flush();
   }
于 2013-07-30T10:36:29.177 回答