user893269
user893269

Reputation: 107

Validate form with Javascript using onsubmit doesn't work

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

Upvotes: 2

Views: 5620

Answers (3)

shawnpwalsh
shawnpwalsh

Reputation: 11

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

Upvotes: 1

Jonah Katz
Jonah Katz

Reputation: 5288

You need id=username because you have

document.getElementById("username")

Upvotes: 1

Naftali
Naftali

Reputation: 146302

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;
}

Upvotes: 1

Related Questions