我使用jquery验证器插件来验证我的注册表单。但是,当我尝试检查用户名是否在数据库中时,它不起作用。任何人都可以帮助看看我的代码,让我知道我做错了什么?即使用户名不在数据库中,它也始终显示用户已存在。
我尝试了
中的方法jQuery Validate remote method usage to check if username already exists和JQuery Remote Validation not displaying Error
但它仍然无效。
我的注册jquery功能:
$().ready(function() {
$.validator.addMethod('uniqueUsername', function(value) {
$.ajax({
url: 'http://localhost:8080/TBS-war/RegisterServlet.java',
type: 'POST',
async: false,
contentType: 'application/json',
dataType: 'json'
});
});
//Validate signup form on keyup and submit
$("#registrationForm").validate({
// Set rules
rules: {
username: {
required: true,
uniqueUsername: true
/*remote: {
url: "http://localhost:8080/TBS-war/RegisterServlet.java",
type: "post",
contentType: "application/json",
data: {
'username': $('#username').val()
}
}*/
},
password: {
required: true
},
confirmPassword: {
required: true,
equalTo: "#password"
},
contact: {
required: true
},
email: {
required: true,
email: true
},
address: {
required: true
}},
// Set messages
messages: {
username: {
required: "* This field is required",
uniqueUsername: "* User already exist"
//remote: "* User already exist"
},
password: {
required: "* This field is required"
},
confirmPassword: {
required: "* This field is required",
equalTo: "* Please enter the same password as above"
},
contact: {
required: "* This field is required"
},
email: {
required: "* This field is required",
email: "* Please enter a valid email"
},
address: {
required: "* This field is required"
}},
我的servlet文件:
@EJB
private TBSManagerBeanRemote tBSManagerBean;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
String username = request.getParameter("username");
if (tBSManagerBean.userExist(username)) {
out.print("{\"valid\" : false }");
json.put("valid", false);
System.out.println("false");
}
else {
out.print("{\"valid\" : true }");
json.put("valid", true);
System.out.println("true");
}
}