user3441151 user3441151 - 1 month ago 5
Javascript Question

JavaScript validation not workig on HTML form

I want to validate my jsp form.

My test.jsp page is given below

<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
function validateForm() {
var address = document.getElementById("txtAddress");
alert("Address : " + address);
if (address == null || address == "") {
alert("Enter Address");
return false;

var city = document.getElementById("txtCity");
if (city == null || city == "") {
alert("Enter City");
return false;
<form name="TestForm1" action="loginServlet" method="post" onsubmit="return validateForm();">
<td>Address :</td>
<td><input type="text" name="txtAddress" value="${reqObj.address}" /></td>
<td>City :</td>
<td><input type="text" name="txtCity" value="${}" /></td>
<tr align="left">
<td colspan="4"><input type="submit" value="Submit" /></td>
String createdDate = "";
Date dt = new Date();
createdDate = dt.toString();
System.out.println("currentTime>>>>" + createdDate);

Problem is that,
When run this Project my test.jsp form is displayed with empty Address field and when i click on Submit Button alert is showing "Address : null"

But when i write some value on Address textbox field then i click on Submit Button again it showing me "Address : null"

I am using JAVA with Eclipse Mars 1.

Sam Sam

No id attribute is present in the jsp.

<input type="text" name="txtAddress" value="${reqObj.address}" />

Add id(id="txtAddress") attr and then use document.getElementById("txtAddress");

<input type="text" id="txtAddress" name="txtAddress" value="${reqObj.address}" />

And you can check for length instead of null and ""

if(address.value.trim().length == 0)

Not only using id one can get using class,name,tag also

  • document.getElementById("xyz");

  • document.getElementsByTagName("p");

  • document.getElementsByClassName("abc");

  • document.getElementsByName("xyz");

Update: Mainly you are missing taking value of that element.Take the value and then check