Reputation: 123
i am using jquery.validate.js for validation to identify duplicate entries
this is my custom method
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");
this is my Spring method in controller
@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();
}
}
through this method i able to get data is duplicated or not (through 'matched' variable) , if data is present in database it return same data and if data is not present it return ' [] ' (because i used List type)
my problem is : in if statement condition is wrong, for all data it go to else block even if their is no data (i.e 'matched' variable return ' [] ') . and how to set that status in custom validation method
thanks in advance.
Upvotes: 2
Views: 259
Reputation: 1933
Replace your ajax method
$.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");
Upvotes: 2
Reputation: 3676
String s = "[]";
if(s.equals(matched))
This is not the way to check if a list is empty or not instead use matched.isEmpty()
with a not null check .So your condition will be
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();
}
Upvotes: 0