I need to validate a name field to validate if the name field is empty and if the name existed in my database. If it passes both the validation(the user has input a name that is not existed in my database), then the form will be submitted.
The problem is with my validation of name existed in my database. I used ajax and even though I used e.preventDefault() to stop the form from submitting if the name existed in the success block, it just pops up an alert "name existed" and proceed to submit the form.
Please help.
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="https://code.jquery.com/jquery-3.1.1.js"></script> <script src="validateForm.js"></script> <title>Validate Form</title> </head> <body> <form id="form" name="form" action="FormCheck" method="POST">
Name: <input id="name" type="text" name="name"><br> <input id="btn" type="submit" value="Submit"> <div> <span id="errorMsg" style="display: none;"></span> </div> </form> </body> </html>
validateForm.js
$(document).ready(function() {
/*
* $("#btn").click(function(e) {
*
* });
*/
$("#form").submit(function(e) {
validateEmptyField(e);
validateEmailExisted(e);
});
});
function validateEmptyField(e) {
if (!$("#name").val().length) {
e.preventDefault();
alert("name Field is required");
}
}
function validateEmailExisted(e) {
dataString = $("#form").serialize();
dataString = "name=" + $("#name").val();
$.ajax({
type : "POST",
url : "FormCheck",
data : dataString,
dataType : "json",
success : function(data) {
if (data.success) {
//alert(data.value.name);
if(data.value.name === $('#name').val()) {
e.preventDefault();
alert("name existed");
}
}
}
});
}
FormCheck.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class FormCheck extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
System.out.println(name);
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
FormField formField = getNameInDB(name);
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
JsonElement jsonElement = gson.toJsonTree(formField);
if (name.equals(formField.getName())) {
myObj.addProperty("success", true);
}
myObj.add("value", jsonElement);
out.println(myObj.toString());
out.close();
}
public FormField getNameInDB(String name) {
FormField formField = new FormField();
final String DBDRIVER = "com.mysql.jdbc.Driver";
final String DBURL = "jdbc:mysql://localhost:3306/project";
final String DBUSERNAME = "root";
final String DBPASSWORD = "password";
String query = "";
PreparedStatement ps = null;
Connection conn = null;
try {
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
query = "SELECT name FROM Customer WHERE name = ?";
try {
ps = conn.prepareStatement(query);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
formField.setName( rs.getString("name").trim());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return formField;
}
}
FormField.java
public class FormField {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Validation</display-name> <servlet> <servlet-name>FormCheck</servlet-name> <servlet-class>FormCheck</servlet-class> </servlet> <servlet-mapping> <servlet-name>FormCheck</servlet-name> <url-pattern>/FormCheck</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>