...

View Full Version : Javascript validation form



nojo191
08-20-2008, 04:43 AM
Hi, I'm trying to validate a form using the javascript tutorial here (http://www.php-mysql-tutorial.com/form-validation-with-php.php).

There is an example here (http://www.php-mysql-tutorial.com/contact.php), but I can't seem to duplicate the results, not sure why.


<script language="JavaScript">
function checkForm()
{
var cname, cemail, csubject, cmessage;
with(window.document.contactform)
{
cname = name;
cemail = email;
csubject = subject;
cmessage = message;
}

if(trim(cname.value) == '')
{
alert('Please enter your name');
cname.focus();
return false;
}
else if(trim(cemail.value) == '')
{
alert('Please enter your email');
cemail.focus();
return false;
}
else if(!isEmail(trim(cemail.value)))
{
alert('Email address is not valid');
cemail.focus();
return false;
}
else if(trim(csubject.value) == '')
{
alert('Please enter message subject');
csubject.focus();
return false;
}
else if(trim(cmessage.value) == '')
{
alert('Please enter your message');
cmessage.focus();
return false;
}
else
{
cname.value = trim(cname.value);
cemail.value = trim(cemail.value);
csubject.value = trim(csubject.value);
cmessage.value = trim(cmessage.value);
return true;
}
}

/*
Strip whitespace from the beginning and end of a string
Input : a string
*/
function trim(str)
{
return str.replace(/^\s+|\s+$/g,'');
}

/*
Check if a string is in valid email format.
Returns true if valid, false otherwise.
*/
function isEmail(str)
{
var regex = /^[-_.a-z0-9]+@(([-a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
//regex = /^[-_.abcdefghijklmnopqrstuvwxyz0123456789]+@(([-abcdefghijklmnopqrstuvwxyz0123456789]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
return regex.test(str);
}
</script>

and the form code:


<form name="contact_form" id="contact_form" method=post action="contact_submit.php">
<table border="0" ALIGN="CENTER" cellpadding="3" cellspacing="0" style='font-family: Tahoma; font-size: 9pt;'>
<tr align="center" valign="middle">
<td colspan="2"><em><font size="1">An asterisk <font color="#FF0000">*</font>

indicates a required field</font></em></td>
</tr>
<tr>
<td align="left">Company Name:</td>
<td align="left" valign="middle"> <input type="text" name="company" size="35" style='width: 250px; font-family: Tahoma; font-size: 9pt;'>
</td>
</tr>

<tr>
<td align="left"><font COLOR="#FF0000" size="2" face="Tahoma, Arial, Helvetica, sans-serif">*</font>Contact
Name:</td>
<td align="left" valign="middle"> <input type="text" name="name" id="name" size="35" style='width: 250px; font-family: Tahoma; font-size: 9pt;'>
</td>
</tr>
<tr>
<td align="left"><font COLOR="#FF0000" size="2" face="Tahoma, Arial, Helvetica, sans-serif">*</font>Contact
Phone Number:</td>

<td align="left" valign="middle"> <input type="text" name="phone" id="phone" size="35" style='width: 250px; font-family: Tahoma; font-size: 9pt;'>
</td>
</tr>
<tr>
<td align="left"><font COLOR="#FF0000" size="2" face="Tahoma, Arial, Helvetica, sans-serif">*</font>&nbsp;Contact
Email Address:</td>
<td align="left" valign="middle"> <input type="text" name="email" id="email" size="35" style='width: 250px; font-family: Tahoma; font-size: 9pt;'>
</td>

</tr>
<tr>
<td align="left"><font COLOR="#FF0000" size="2" face="Tahoma, Arial, Helvetica, sans-serif">*</font>Topic of Inquiry:</td>
<td align="left" valign="middle"> <input type="text" name="subj" id="subj" size="35" style='width: 250px; font-family: Tahoma; font-size: 9pt;'>
</td>
</tr>
<tr>
<td align="left" valign="top"><font COLOR="#FF0000" size="2" face="Tahoma, Arial, Helvetica, sans-serif">*</font>Please describe your interest<BR>in our products and services:</td>

<td align="left" valign="top"> <textarea name="comments" id="comments" cols="30" rows="8" wrap="VIRTUAL" style='width: 250px; font-family: Tahoma; font-size: 9pt;'></textarea>
</td>
</tr>
<tr>
<td colspan=2 align=center> <input type="submit" value="Submit Contact Form" onClick="return checkForm();">
</td>
</tr>

</table>
</form>


Probably a stupid mistake, but thanks for any help.

Philip M
08-20-2008, 09:21 AM
...but I can't seem to duplicate the results, not sure why.

with statements are deprecated and unreliable.
Replace this:-



function checkForm()
{
with(window.document.contactform) // the name and id of the form is contact_form
{
cname = name;
cemail = email;
csubject = subject; // this field is named subj
cmessage = message;
}

With this:-


function checkForm() {
var cname, cemail, csubject, cmessage;
cname = document.getElementById("name");
cemail = document.getElementById("email");
csubject = document.getElementById("subj"); // note field is named subj
cmessage = document.getElementById("message");
}



and replace

<script language="JavaScript">
by
<script type = "text/javascript">

Your email validation regex is somewhat over-complicated - I would suggest:-

var regex = /^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@(([\w\-]?)+\.)+([a-z]{2,4})$/

There is really no point in over-complicated validation of email adddresses, telephone numbers and so forth, as nothing can prevent the most obvious and common source of errors, that is simple mistyping e.g.
philip@myadddress.com.
It is better to request that the user inputs his email address twice by way of confirmation, and check that the two match.




It is your responsibility to die() if necessary….. - PHP Manual

nojo191
08-20-2008, 10:57 PM
I don't get it. I created a test page and put the whole pages code on that after i edited it as philip suggested (thanks!), then deleted everything but the javascript and the form to see if it was something else influencing it. and it clearly wasn't since it still submitted.

It works just fine in this bit...


<html>
<head>
<title>PHP MySQL Tutorial : Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="/styles/1/styles.css">
<meta name="keywords" content="contact form php mysql tutorial">
<meta name="description" content="This is just the contact form, nothing special">
<meta name="netinsert" content="0.0.1.3.4.4.1">
<script language="JavaScript1.1" type="text/javascript">
<!-- // hide from old browsers
if (parent.frames.length > 0) top.location.replace(document.location); // Escape from any referring site's frame, but preserve one-click "Back".
-->
</script>
</head>
<body>
<!-- google_ad_section_start -->
<table width="650" height="22" border="0" align="center" cellpadding="0" cellspacing="0" background="/images/1/bg1.gif">
<tr>

<td>&nbsp;</td>
</tr>
</table>
<script language="JavaScript">
function checkForm()
{
var cname, cemail, csubject, cmessage;
with(window.document.msgform)
{
cname = sname;
cemail = email;
csubject = subject;
cmessage = message;
}

if(trim(cname.value) == '')
{
alert('Please enter your name');
cname.focus();
return false;
}
else if(trim(cemail.value) == '')
{
alert('Please enter your email');
cemail.focus();
return false;
}
else if(!isEmail(trim(cemail.value)))
{
alert('Email address is not valid');
cemail.focus();
return false;
}
else if(trim(csubject.value) == '')
{
alert('Please enter message subject');
csubject.focus();
return false;
}
else if(trim(cmessage.value) == '')
{
alert('Please enter your message');
cmessage.focus();
return false;
}
else
{
cname.value = trim(cname.value);
cemail.value = trim(cemail.value);
csubject.value = trim(csubject.value);
cmessage.value = trim(cmessage.value);
return true;
}
}

/*
Strip whitespace from the beginning and end of a string
Input : a string
*/
function trim(str)
{
return str.replace(/^\s+|\s+$/g,'');
}

/*
Check if a string is in valid email format.
Returns true if valid, false otherwise.
*/
function isEmail(str)
{
var regex = /^[-_.a-z0-9]+@(([-a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
//regex = /^[-_.abcdefghijklmnopqrstuvwxyz0123456789]+@(([-abcdefghijklmnopqrstuvwxyz0123456789]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
return regex.test(str);
}
</script>
<table width="650" border="0" align="center" cellspacing="0">
<tr>
<td background="images/1/bg2.gif" class="maincell"><div align="center" class="errmsg"></div>
<form method="post" name="msgform" id="msgform">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="1" class="maincell">
<tr>
<td width="106">Your Name</td>

<td width="381"><input name="sname" type="text" class="box" id="sname" size="30" value=""></td>
</tr>
<tr>
<td>Your Email</td>
<td><input name="email" type="text" class="box" id="email" size="30" value=""></td>
</tr>
<tr>
<td>Subject</td>
<td><input name="subject" type="text" class="box" id="subject" size="30" value=""></td>

</tr>
<tr>
<td>Message</td>
<td><textarea name="message" cols="55" rows="10" wrap="PHYSICAL" class="box" id="message"></textarea></td>
</tr>
<tr align="center">
<td colspan="2"><input name="send" type="submit" class="bluebox" id="send" value="Send Message" onClick="return checkForm();"></td>
</tr>
<tr align="center">
<td colspan="2">&nbsp;</td>

</tr>
<tr align="left">
<td colspan="2"><p>If by any chance the form isn't working you can contact
me on <br>
<script language="JavaScript">
var addr = 'arman';
var host = 'php-mysql-tutorial.com';
var email = '<a href="mailto:' + addr + '@' + host + '">' + addr + '@' + host + '</a>';
document.write(email);
</script>
<br>
</p>
<p>Note : Please forgive me if i can't respond to
you promptly. I have a day job and sometime i'm
just too tired to read the emails.</p></td>
</tr>

</table>
</form>
<p>&nbsp;</p></td>
</tr>
</table>

<!-- google_ad_section_end -->
<!-- google_ad_section_start(weight=ignore) -->
<table width="650" border="0" align="center" cellspacing="0">
<tr>
<td background="/images/1/bg2.gif" class="maincell">
<p align="center"><a href="http://www.scriptlance.com/cgi-bin/freelancers/r.cgi?arman198" rel="nofollow"><img src="http://www.scriptlance.com/banners/keybanner.gif" width=468 height=60 alt="Get custom programming done at ScriptLance.com!" border=0></a></p>
</td>
</tr>

</table>
<table width="650" height="22" border="0" align="center" cellpadding="0" cellspacing="0" background="/images/1/bg3.gif">
<tr>
<td>&nbsp;</td>
</tr>
</table>

<br>
<br>
<p align="center">
Copyright &copy; 2004 - 2008 <a href="http://www.php-mysql-tutorial.com">www.php-mysql-tutorial.com</a> | <a href="/privacy.html">Privacy Policy</a>

</p>

<!--- google analytics start --->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-96716-2");
pageTracker._initData();
pageTracker._trackPageview();
</script>

<!--- google analytics end --->

<!--- google adsense tracker start --->
<script src="/astrack.js" type="text/javascript"></script>
<!--- google adsense tracker end --->

<!-- google_ad_section_end -->
</body>

</html>

Philip M
08-21-2008, 08:37 AM
Please say exactly what the problem is, and what error messages (if any) you receive. It is not much use posting the code which does work - what is it that you think does not work?

I should say that having made the alterations which I suggested the form is working fine for me, although there is no validation of the phone number which is supposed to be a required field.

I have just noticed another defect:-

<td align="left" valign="top"> <textarea name="comments" id="comments" cols="30" rows="8" wrap="VIRTUAL" style='width: 250px; font-family: Tahoma; font-size: 9pt;'></textarea>

Replace "comments" by "message" - which is the id reference in the script.

An improvement would be to replace all these tests:-

if (trim(cname.value) == '') // a single character such as * will pass the test
by
if(trim(cname.value.length) < 6) // minimum 6 characters or whatever is felt appropriate in each case

chaosprime
08-21-2008, 10:56 AM
Hint: run it in Firefox and look at Tools > Error Console.

nojo191
08-22-2008, 12:40 AM
Sorry for the confusion. The last bit of javascript I provided was the sample tutorial that I'm working from. Everything there works. I'm trying to incorporate that into my own website. I'm not getting any errors at all. That's the problem. I'm supposed to receive a javascript popup, and I'm not getting one. The html form is the same as I posted earlier, but I did make the comments/message fix (thanks!). I also updated the javascript and I'm still not getting the popup message.

The phone number also needs a validation but I've never actually coded much JS, so I'm not sure how to go about it...

The error console tells me that on line 29 (of the whole page that is) "return not in function".


<script type="text/javascript">
function checkForm() {
var cname, cemail, csubject, cmessage;
cname = document.getElementById("name");
cemail = document.getElementById("email");
csubject = document.getElementById("subj"); // note field is named subj
cmessage = document.getElementById("message");
}
if(trim(cname.value.length) < 6)
{
alert('Please enter your name');
cname.focus();
return false; // return error here
}
else if(trim(cemail.value.length) < 3)
{
alert('Please enter your email');
cemail.focus();
return false;
}
else if(!isEmail(trim(cemail.value)))
{
alert('Email address is not valid');
cemail.focus();
return false;
}
else if(trim(csubject.value.length) < 3)
{
alert('Please enter message subject');
csubject.focus();
return false;
}
else if(trim(cmessage.value.length) < 6)
{
alert('Please enter your message');
cmessage.focus();
return false;
}
else
{
cname.value = trim(cname.value);
cemail.value = trim(cemail.value);
csubject.value = trim(csubject.value);
cmessage.value = trim(cmessage.value);
return true;
}
}

/*
Strip whitespace from the beginning and end of a string
Input : a string
*/
function trim(str)
{
return str.replace(/^\s+|\s+$/g,'');
}

/*
Check if a string is in valid email format.
Returns true if valid, false otherwise.
*/
function isEmail(str)
{
var regex = /^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@(([\w\-]?)+\.)+([a-z]{2,4})$/;
return regex.test(str);
}
</script>

chaosprime
08-22-2008, 02:44 AM
The 'return not in function' is because there's a closing brace that shouldn't be there, on the line before your first if.

nojo191
08-22-2008, 03:18 AM
I don't know what else I could possibly do to make this thing work. I've fixed that problem, and I'm not getting any more errors in the error console anymore, so that's good at least.

chaosprime
08-22-2008, 03:24 AM
Well, you've got some more breakage in that you're doing
document.getElementById("name"); but the ID on the element is sname.

Nothing shows up in the error console after you click the submit button? That seems hard to believe.

nojo191
08-22-2008, 03:32 AM
ah ha, AFTER I submit the form. now there's my problem. *bangs head against wall*

My copy here that I'm working with shows "name" as the ID, so maybe you're looking at the tutorial copy I posted? I am getting a str.replace is not a function error now on line 71, which is...

return str.replace(/^\s+|\s+$/g,'');

chaosprime
08-22-2008, 03:42 AM
What that really means is that str isn't what you think it is. And well it might not be... you're saying in your various if/elses things like:
trim(cname.value.length)
when what you mean is

trim(cname.value).length

nojo191
08-22-2008, 03:47 AM
Works like a charm, thanks so much chaos! How should I verify the phone number?

chaosprime
08-22-2008, 04:00 AM
You're welcome. There's a forum thanks feature too and all. :)

If you're comfortable requiring that the phone number be precisely NNN-NNN-NNNN format, you could use a regex like whateverstr.match(/^\d{3}-\d{3}-\d{4}$/). Complexity increases the more forgiving you want it to be.

nojo191
08-22-2008, 04:05 AM
thanked. :thumbsup: So what would be the string to support dashes, spaces, OR nothing at all between the numbers? Is this to complicated to ask for help with?

chaosprime
08-22-2008, 04:07 AM
Nah, 'sfine. That'd be /^\d{3}[- ]?\d{3}[- ]?\d{4}$/.

nojo191
08-22-2008, 04:10 AM
awesome, I think I can call this one solved. thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum