2

i tried to find any helpful post for my problem, but didn't find so my question: i want to validate form before submit it to data base. and this is my code:

<%@ page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Registration</title>
<link rel="shortcut icon" href="img/icon0.png" />
<link rel="stylesheet" type="text/css" href="../css/index.css" />
<script type="text/javascript">
function validate_form()
{
var isValid = true;
var username = document.getElementById("username").value;
if (username==null||username==""){
    alert("WRong input");
    isValid = false;
}
if(isValid == true)
{
    return true;
}
return false;
}
</script>
</head>
<body>
<form action = "regServlet" method = "POST" onsubmit="return validate_form()">
<table id="regTable">
  <tr>
    <td class="firstRow">Username:</td>
    <td><input type="text" name="username" value="" size="15"/></td>
  </tr>
</table>
<input style="margin:auto;" type="image" name="loginB" src="../img/login_button.png" />
</form>
</body>
</html>

it's jsp file that runs in tomcat 6. when i'm running the page, my javascript function doesn't work at all. I checked it with alert in the start of the function. what is my problem? what i forgot? Eclipse writes an error on form line (where onsubmit is appears): cannot return from outside a function or method.

thanks

1
  • Is that the code as it's rendered? Commented Aug 17, 2011 at 19:20

3 Answers 3

1

You need id=username because you have

document.getElementById("username")
Sign up to request clarification or add additional context in comments.

Comments

1

You need to give your input with name="username" also an id="username"

DEMO: http://jsfiddle.net/maniator/tf5zA/

And your js could be cleaner:

function validate_form() {
    var isValid = true;
    var username = document.getElementById("username").value;
    if (username == null || username == "") {
        alert("WRong input");
        isValid = false;
    }
    return isValid;
}

Comments

1

I also came across the "Cannot return from outside a function or method." and found a filed validation bug in Eclipse WTP at https://bugs.eclipse.org/bugs/show_bug.cgi?id=353209

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.