...

View Full Version : Unable to validate html forms using external javascript



sunil_2215
03-24-2009, 04:56 PM
Hi guys..

I am a newbie trying to generate an alert message when a user leaves a username filed blank in an html form using an external javascript.

Following is the code for html file.


<HTML>
<TITLE>trial alert</TITLE>
<HEAD>
<script language="JavaScript" src="sample.js" type="text/javascript"></script>
</HEAD>

<BODY>
<form name = "myform" onSubmit = "test()">
<P>
Username : <INPUT TYPE="text" Username ="visitor_username" SIZE="20"
hspace="20"><br>
First Name: <INPUT TYPE="text" FIRST NAME="visitor_name" SIZE="20"
hspace="20"><br>

<INPUT TYPE="radio" NAME="gender1" VALUE="male"> Male<br>
<INPUT TYPE="radio" NAME="gender2" VALUE="female"> Female<br>

<INPUT TYPE="submit" VALUE="submit">
</form>
</BODY>
</HTML>


The code for the external javascript file is:


function test(){
if(document.myform.visitor_username.value==""){
alert("enter a username");
}
}


However, if I swap the positions of the username and first name i.e. place the first name before the username, I do get an alert message if the first name is left empty.

Folks, I do not wish to hijack an existing thread. Please let me know if there is an existing thread on this issue..(I could not find one).
Please advice.
Thanks.

TinyScript
03-24-2009, 05:04 PM
There is a thread somewhere, but I saved the script from it anyway, so here. You should be able to pick out what you need. I didn't write it.



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Any Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

var alertImgs = [];
var nImage = "";

function validate(nForm){

for (i=0; i<alertImgs.length; i++)
{
nImage[alertImgs[i]].style.visibility = "hidden";
}
var nFirstName = nForm['firstName'];
var nSurName = nForm['surName'];
var nMobile = nForm['mobile'];
var nEmail = nForm['email'];
if (nFirstName.value.replace(/\s/g, "").length < 1)
{
document.images[alertImgs[0]].style.visibility = "visible";
setTimeout( doAlert0,1000);

return false;
}
if (nSurName.value.replace(/\s/g, "").length < 1)
{

document.images[alertImgs[0]].style.visibility = "visible";
setTimeout( doAlert1,1000);
return false;
}
if (!/[\d\s-]+$/.test(nMobile.value) || !/\d{10}/.test(nMobile.value.replace(/[\s-]/g, ""))) // must contain 10 digits;
{

document.images[alertImgs[0]].style.visibility = "visible";
setTimeout( doAlert2,1000);
return false;
}
if (!/^\w+[\w|\.|\-]{0,1}\w*[\w|\.|\-]{0,1}\w*\@\w+[\w|\-]{0,1}\w*[\w|\-]{0,1}\w*\.{1,1}[a-z]{2,4}$/.test(nEmail.value))
{

document.images[alertImgs[0]].style.visibility = "visible";
setTimeout( doAlert3,1000);
return false;
}
if (nForm['comments'].value == "")
{

document.images[alertImgs[0]].style.visibility = "visible";
setTimeout( doAlert4,1000);
return false;
}
alert('Thank you for your submission');
return true;
}
function doAlert0(){alert('Please enter your first name')}
function doAlert1(){alert('Please enter your last name');}
function doAlert2(){alert('Please enter your mobile phone number');}
function doAlert3(){alert('Please enter a valid Email');}
function doAlert4(){alert('Please write a comment');}
function init(){

nImage = document.images;
var imgFileName = "";
for (i=0; i<nImage.length; i++)
{
imgFileName = nImage[i].src;
imgFileName = imgFileName.substring(imgFileName.lastIndexOf("/")+1,imgFileName.length)
//if (imgFileName == "http://i43.tinypic.com/20kswnl.gif")
//{
alertImgs[alertImgs.length] = i;
nImage[i].style.visibility = "hidden";
//}
}
}

navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);


</script>
<style type="text/css">

body {background-color: #fffacd; margin-top: 60px;}
form {width: 350px; margin: auto; font-family: 'times new roman'; font-size: 12pt;}
fieldset {width: 350px; padding-left: 10px; background-color: #eee8aa; border: 1px solid #e6b280;}
legend {font-family: arial; font-size: 14pt; color: #000000; background-color: transparent; padding-top: 3px;
padding-left: 3px; padding-right: 3px; margin-bottom: 5px;}
label {font-family: tahoma; font-size: 11pt; color: #00008b; padding: 5px; display: block;}
p {font-family: tahoma; font-size: 7pt; color: #ff0000; }
p2 {font-family: tahoma; font-size: 11pt; color: #00008b; }
.comment {font-family: arial; font-size: 10pt; margin-left: 48px; overflow: hidden;}
.alertImg {margin-left: 3px;}
.submitBtn {background-color: #fff8dc; border: 1px solid #000000; font-family: arial; font-size: 10pt;
font-weight: bold; cursor: pointer; display: block; margin-left: auto; margin-right: auto;
margin-top: 5px; margin-bottom: 5px;}

</style>
</head>
<body>
<form action="" method="post" onsubmit="return validate(this)">
<fieldset>
<legend>Comment Box</legend>
<label>First Name: <input type="text" name="firstName" size="42" class=""></label>
<label>Last Name: <input type="text" name="surName" size="42" class=""></label>
<label>Phone # : <input type="text" name="mobile" size="42" class=""></label>
<label><p><p2>Your Email:</p2> * Your Email will remain private</p><input type="text" name="email" size="42" class=""></label>
<label><p><p2>Comments:</p2>* Keep your comments nice, please</p></label>
<textarea rows="5" cols="42" name="comments" class="comment"></textarea>
<input type="submit" name="submit" value="Submit" class="submitBtn">
<center><img src="http://i43.tinypic.com/20kswnl.gif" class="alertImg"></center>
</fieldset>
</form>
</body>
</html>

itsallkizza
03-24-2009, 05:08 PM
Here you go:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/" />
<style type="text/css">
body
{
font-size: 12px;
}
</style>
<script type="text/javascript">
// <![CDATA[

function onFormSubmit(form_element)
{
var ok = true;
var error_msgs = new Array();

if (!form_element.visitor_username.value)
{
error_msgs.push("Please enter a valid username.");
ok = false;
}
if (!form_element.visitor_name.value)
{
error_msgs.push("Please enter a valid name.");
ok = false;
}
if (!form_element.gender[0].checked && !form_element.gender[1].checked)
{
error_msgs.push("Please select a gender.");
ok = false;
}

document.getElementById("error_message").innerHTML = error_msgs.join("<br />");
return ok;
}

// ]]>
</script>
</head>
<body>

<form onsubmit="return onFormSubmit(this)">
<input type="text" name="visitor_username" /><br />
<input type="text" name="visitor_name" /><br />
Male:<input type="radio" name="gender" value="m" /> &nbsp; Female:<input type="radio" name="gender" value="f" /><br />
<input type="submit" value="submit" />
</form>

<div id="error_message" style="color:#ff0000;"></div>

</body>
</html>

You can throw the red JS into an external file and it will work exactly the same.

Philip M
03-24-2009, 05:17 PM
Try this as another alternative:-


<HTML>
<TITLE>trial alert</TITLE>
<HEAD>
</HEAD>

<BODY>
<form name = "myform" onSubmit = "return test()">

Username : <INPUT TYPE="text" name ="visitor_username" SIZE="20"
hspace="20"><br>
First Name: <INPUT TYPE="text" name ="visitor_name" SIZE="20"
hspace="20"><br>

<INPUT TYPE="radio" NAME="gender" VALUE="male"> Male<br>
<INPUT TYPE="radio" NAME="gender" VALUE="female"> Female<br>

<INPUT TYPE="submit" VALUE="submit">
</form>

<script type = "text/javascript">

function test(){
var un = document.myform.visitor_username.value;
un = un.replace(/^\s+|\s+$/g,""); // strip leading and trailing sapces
un = un.replace(/[^a-z0-9]/gi,""); // strip characters apart from a-z A-Z 0-9 (no ? * ! $ etc. allowed)
if (un.length < 4) {
alert ("User name must be at least three characters");
return false
}

var visn = document.myform.visitor_name.value;
visn = visn.replace(/^\s+|\s+$/g,""); // strip leading and trailing sapces
visn = visn.replace(/[^a-z'-]/gi,""); // strip characters apart from a-z apostrophe hyphen Mary-Lou Tom O'Flanaghan
if (visn.length < 2) {
alert ("Visitor name must be at least two characters");
return false;
}

if ((document.myform.gender[0].checked == false) && (document.myform.gender[1].checked == false)) {
alert ("You must select your gender");
return false;
}
return true; // this is the default so not actually required
}
</script>
</BODY>
</HTML>

Note that I have stripped leading and trailing spaces and eliminated inappropriate characters. Also specified a minimum length to avoid accepting a single letter. Naturally you can alter this to taste.
Validations of the form if (username == "") or if (!username) are hardly worthy of the name as even a single space or a ? will return false (i.e. pass the validation).

Note also that all the radio buttons in a group must have the same name.


Tourist in hotel in Jasper, Alberta, Canada: " Do we need to convert our Canadian currency into British pounds when we go on to British Columbia?"

sunil_2215
03-24-2009, 07:25 PM
Thanks guys for your inputs...
It sure has helped me a lot.:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum