简体   繁体   中英

validation on JSP page does not work

I have the following jsp page with one input textbox, upon entering the number, the page is redirected to a servlet where I retrieve that number and let's say display it on a page. I'm trying to do the validation in JavaScript but in spite of it, it's still executing the servlet even though validation returns false and I get java.lang.NumberFormatException: For input string: "" in the doGet method on the servlet on the following line: int max = Integer.parseInt(request.getParameter("lengthTxt")); . Why does it seem to bypass validation and still execute the servlet ? How to fix it ? thanks for help !

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function validateForm()
{
    if(document.frm.lengthTxt.value=="")
    {
      alert("Number should not be left blank");
      document.frm.lengthTxt.focus();
      return false;
    }

}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Length calc</title>
</head>
<body>
<h3>enter length</h3>
<form name=frm action="MyServlet" onSubmit="return validateForm();">

    <input name="lengthTxt" />
    <br>
    <br>
    <input type = "submit" value = "Submit"/>

</form>

</body>
</html>

This seems insane.After checking this code on some browsers.It will execute form submit event even the the onsubmit returned with a false value like this.

onsubmit="return validateForm()";

So that you can prevent further form exection with event.preventDefault() function.

So that using Conditional Statement in onsubmit will save the day.Below goes the full statement to be used.

<form onsubmit="event.preventDefault(); return validateMyForm();">

Anything more,jz comment.

if you given wrong name in field to focus then it happens otherwise it should be work fine. please check again in java Script function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM