Validate form with Javascript using onsubmit doesn't work - javascript

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

You need id=username because you have
document.getElementById("username")

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

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

Related

Opening a local HTML page through javascript

I have this html code where the index.html loads first. It has a text field and a submit button. When the submit button is clicked, it calls the validateForm() function. Suppose the text field is empty, it should alert that it is empty, if it isn't then a new html page would load (either in new tab or current one) which is supposed to be welcome.html
So my problem is, the welcome.html file isn't loading. I even changed the "welcome.html" in window.location.href = "welcome.html" to "https://www.google.com" . The page still wouldn't load. What's wrong and what am I missing here ?
Any help is appreciated.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
<script src="/validateForm.js"></script>
</head>
<body>
<form method="get" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
validateForm.js
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
}
else {
window.location.href = "welcome.html";
}
}
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome :)</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
Use action attribute
You can use the action attribute on the form to forward to a URL on success:
<form method="get" action="welcome.html" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
Documentation: MDN - Form action attribute
return value of validateForm()
See this?
onsubmit="return validateForm()"
Your validateForm doesn't return anything.
It is convention that return false means "stop processing the form" and a true-ish value means continue, which in turn means the action attribute mentioned above leads to welcome.html as you wanted.
The modified function could be this:
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
return false;
}
return true;
}
Alternatively, give validateForm a first parameter named event and call event.preventDefault() instead of returning false.
Documentation: MDN - Form submit handling example
You need some changes in index.html file and validateForm.js file
index.html
<form method="get" onsubmit="return validate()" action="javascript::window.location.replace('welcome.html')">
...
</form>
and in validateForm.js
you need to return true or false
after validation function if true it redirects to welcome.html or if false nothing were heppened.

How to "onclick="location.href=''" for html button, for user login, only after validating credentials?

I am trying to make a login page for a web app.
How do I only allow onclick="" of a button once the username and password have been validated?
Below is what I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Customer Login</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Language" content="ch-cn">
<script>
function validate() {
var uname = document.getElementById("uname");
var upass = document.getElementById("upass");
if(uname.value == ""){
alert("username can't be null");
return false;
}
else if(upass.value ==""){
alert("password can't be null");
return false;
}
else
return true;
}
</script>
</head>
<body>
This is the Customer login page.
<br>
<form method="post" action="custlogin">
user SSN:<input type="text" id="uname" name="userSSN"><br>
<br> password:<input type="password" id="upass" name="pwd"><br>
<br>
<button type="submit" value="submit" onclick="return validate();">submit</button>
<button type="reset" value="reset">reset</button>
</form>
</body>
</html>
Where are you storing the info for what valid usernames and passwords are?
A database?
I am attempting to help, but I am no expert.
To my understanding would need to test the values of the inputs against the value of what is already saved in your Database.
something like
have the form fields with ids userName , passWord
if {
userName == howeverYouReferenceAusernameindb
&& passWord == #tablename.columnName
{
login code here
}
else { "please put valid creds"
}
}

JavaScript form-validate without alert

What is wrong with my JavaScript? I want to show a errormessage next to the validate-field, but it doesnt show anything.
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="jsformular.js"></script>
<meta charset="utf-8">
</head>
<body>
<div id="formBody">
<form name="myform" onsubmit="return validate()" method="post">
<div class="formField">
<div class="formFieldElement">
<label for="firstname">Firstname:*</label>
</div>
<div class="formFieldElement">
<input type="text" name="firstname">
</div>
<div class="formFieldElement formError" id="errorFirstname"></div>
</div>
</form>
</body>
</html>
you lost } in validate function
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
}
it's work
You were missing the close bracket at the end of your function.
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
}
When I typed nothing in the field and hit the enter key, it showed the error message.
For finding issues like this in future, I would highly recommend using the developer console included with Chrome or Firefox. It immediately flagged the error for me with the following error message:
Uncaught SyntaxError: Unexpected end of input

object oriented javascript form registeration

i am new to the object oriented javascript :)
i have written this code to validate the first name of a registration form, but it is not working
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OOForm</title>
<meta name="author" content="engy" />
<!-- Date: 2015-02-20 -->
<script>
var Form = {
fname:{
minLength : 1,
maxLength : 15,
},
validateLength:function(formEl,type){
if(formEl.value.length>type.maxLength||formEl.value.length<type.minLength){
document.getElementById("firstNameSpan").innerHTML = "<font color='red'>Invalid User Name</font>";
return false;
}
else{
document.getElementById("firstNameSpan").innerHTML = "";
return true;
}
},
};
function checkForm(){
var ourForm = document.getElementById("ourForm");
var inputs = ourForm.getElementsByTagName("input");
if(Form.validateLength(inputs[0],Form.fname)){
document.getElementById("mySubmit").disabled = false;
return true;
}
document.getElementById("mySubmit").disabled = true;
return false;
}
</script>
</head>
<body>
<form id="ourForm">
<label>First Name</label>
<input type="text"/>
<span id="firstNameSpan"> </span>
<br/>
<input type="submit" value="submit" id="mySubmit" onclick="return checkForm()">
</form>
</body>
</html>
i don't know what is the problem with the code, but when i enter the firstname with invalid value and then press submit, it do nothing but clearing the text field
and the "invalid" span do not appear
I think it's because you need to do onsubmit on form element instead of onclick and you need to return false in onsubmit so browser won't try to send your form.

Why does Firefox 5 send the form to the server when onsubmit = false with external javascript?

I have a form that I want to validate looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="scripts/validate.js"></script>
</head>
<body>
<form name="frmRegister" method="post" action="register.aspx" onsubmit="return validate(this);">
<div>
<label for="txtUsername">Username:</label>
<input type="text" name="txtUserName" id="txtUserName" size="12" />
</div>
<div>
<label for="txtPassword">Password: </td></label>
<input type="password" name="txtPassword" id="txtPassword" size="12" />
</div>
<div>
<label for="txtPassword2">Confirm your password:</label>
<input type="password" name="txtPassword2" id="txtPassword2" size="12" />
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
</body>
</html>
and the validate function in an external file called validate like this:
function validate(form) {
var returnValue = true;
var username = form.txtUserName.value;
var password1 = form.txtPassword.value;
var password2 = form.txtPassword2.value;
if(username.length < 6) {
returnValue = false;
alert("Your username must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtUserName.focus();
}
if (password1.length < 6) {
returnValue = false;
alert("Your password must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
}
if (password1 != password2) {
returnValue = false;
alert("Your password entries did not match.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
}
return returnValue;
}
But Firefox 5 keeps sending it to register.aspx even though the form doesnt pass the test?
You haven't defined frmRegister.
Internet Explorer will (depending, IIRC, on the version and if you are in quirks mode or not) spew a global variable into existence for every element with an id (and some with a name). Other browsers won't.
When you try things like:
frmRegister.txtPassword.value = "";
The browser will error because frmRegister is undefined so can't have a .txtPassword.
When it errors, the script dies and the return statement is never reached.
Since return is never reached, the submission isn't canceled, and the form is sent to the server as normal.
Try, instead of returning validate(this), returning false. If the form is not submitted then, try returning validate(this), but, in that function, before actually returning the returnValue, try alerting it to make sure it's actually false. Maybe it's due to your focusing elements. Maybe you could first return the returnValue, but do the focussing via setTimetout('focus()', intervalInMillisecons)?
Also, try it in other browsers like Safari or Chrome and see if you get the same results.
Also, try temporarily removing the DOCTYPE. Works wonders sometimes.

Categories