Forum Moderators: open

Message Too Old, No Replies

form validation

         

jpolsonb

7:05 am on Nov 4, 2009 (gmt 0)

10+ Year Member



Hi my name is jamie and I am having a problem with form validation.

I have a simple form with comments, name, email, phone number and recaptcha.

The function validateFormOnSubmit should change the invalid input's backgoung clour to green and display an alert with the error that was returned from the validation functions for each input if the set requiremnents were not met.

The form and recaptcha function correctly and the invalid fields change colour, however the alert is not displayed if there is an error. The lack of alert means it is possible for the user to send a message with blank fields and does not provide a chance for them to fill in the fields.

Below is the stripped down code for contact.php, if you need moe info I am happy to provide it. I also realise I will need new keys for my recaptcha. Thankyou, any advice would be greatly appreciated.

CONTACT.PHP-----------------------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
include('config.php');
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>All About Soakwells - Contact All About Soakwells for a Free Quote</title>
<link href="css/styles1.css" rel="stylesheet" type="text/css" />
<link rel="icon" href="/favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};

function validateFormOnSubmit(theForm) {
var reason = "";

reason += validateUsername(theForm.name);
reason += validateComments(theForm.comments);
reason += validateEmail(theForm.emaile);
reason += validatePhone(theForm.phone);

if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}

return true;
}

function validateEmpty(fld) {
var error = "";

if (fld.value.length == 0) {
fld.style.background = '#339933';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}

function validateComments(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores

if (fld.value == "") {
fld.style.background = '#339933';
error = "Please enter a message.\n";
} else if ((fld.value.length < 1) ¦¦ (fld.value.length > 1000)) {
fld.style.background = '#339933';
error = "Please ent.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = '#339933';
error = "The message contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+¦\s+$/, '');
}

function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores

if (fld.value == "") {
fld.style.background = '#339933';
error = "Please enter your name.\n";
} else if ((fld.value.length < 1) ¦¦ (fld.value.length > 20)) {
fld.style.background = '#339933';
error = "The name is too long.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = '#339933';
error = "The name contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+¦\s+$/, '');
}

function validateEmail(fld) {
var error="";
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

if (fld.value == "") {
fld.style.background = '#339933';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = '#339933';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = '#339933';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = '#339933';
} else if (isNaN(stripped)) {
error = "The phone number contains illegal characters.\n";
fld.style.background = '#339933';
} else if (!(stripped.length == 8)) {
error = "The phone number is the wrong length. Make sure you included an area code.\n";
fld.style.background = '#339933';
}
return error;
}
</script>
</head>
<body id ="contact">
<div id ="container">
<div id="banner">
<img name="banner" src="css/graphics/jpeg/banner1.jpg"
width="100%" alt="All About Soakwells - Perth Western Australia"
style="background-color:#000000;" />
</div>
<div id="right_pane">

<div id= "content">
<h2>Contact All About Soakwells for a Free Quote</h2>
<form name="contact" action="maile.php" method="post" onsubmit="return validateFormOnSubmit(this)">
<fieldset>
<ol>
<li>
<textarea name="comments" rows="8" cols="45" id="comments">
</textarea>
</li>
</ol>
<ol>
<li>
<label for="name">Name :</label>
<input type="text" name="name" class="input" id="name"/>
</li>
<li>
<label for="phone">Phone number :</label>
<input type="text" name="phone" class="input" id="phone"/>
</li>
<li>
<label for="email">Your email address :</label>
<input type="text" name="emaile" class="input" id="emaile"/>
</li>
</ol>
<br/>
<p>Please type the words below. Click the blue refresh button if you have difficulty reading them.</p>
<?php
require_once('recaptchalib.php');
$publickey = "6LdwHQkAAAAAAMDm_yIHHtZRBWWAz8XNd6FnhPoV"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<fieldset class = "submit">
<br/>
<input type="submit" name="Submit" value="Send" style="cursor:pointer"/>&nbsp;
<input type="reset" name="Reset" value="Reset" style="cursor:pointer"/>
<input type="button" name="Back" value="Back" onclick="history.go(-1)" style="cursor:pointer"/>
</fieldset>
</fieldset>
<?php
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);

if ($resp->is_valid) {
echo "You got it!";
} else {
# set the error code so that we can display it
$error = $resp->error;
}
}
echo recaptcha_get_html($publickey, $error);
?>
</form>
</div>
</div>
</div>
</body>
</html>

jpolsonb

7:24 am on Nov 4, 2009 (gmt 0)

10+ Year Member



to test the form go to <snip>

[edited by: Fotiman at 2:14 pm (utc) on Nov. 4, 2009]
[edit reason] No URLs please. See TOS [webmasterworld.com] [/edit]

jpolsonb

11:44 am on Nov 4, 2009 (gmt 0)

10+ Year Member



ok everyting is working now except for the text area "comments" validation. I've spent hours searching and cant see why my code wont work. I feel like I must not be referncing it right but after reading up on the dom it seems that contact.comments should work.

test.hml:

<head>
<script type= "text/javascript" language="JavaScript" src="validate.js"></script>
</head>
<body>
<form name="contact" action="maile.php" method="post" onsubmit="return validateFormOnSubmit(this)">
<fieldset>
<ol>

<li>
<textarea name="comments" rows="8" cols="45" id="comments">
</textarea>
</li>
<li>
<label for="name">Name :</label>
<input type="text" name="name" class="input" id="name"/>
</li>
<li>
<label for="phone">Phone number :</label>
<input type="text" name="phone" class="input" id="phone"/>
</li>
<li>
<label for="emaile">Your email address :</label>
<input type="text" name="emaile" class="input" id="emaile"/>
</li>
</ol>
<br/>

<fieldset class = "submit">
<br/>

<input type="submit" name="Submit" value="Send" style="cursor:pointer"/>&nbsp;
<input type="reset" name="Reset" value="Reset" style="cursor:pointer"/>
</fieldset>
</fieldset>
</form>
</body>
</html>

validate.js-------------------------------------------------

function validateFormOnSubmit(contact) {
var reason = "";

reason += validateComments(contact.comments);
reason += validateName(contact.name);
reason += validateEmail(contact.emaile);
reason += validatePhone(contact.phone);

if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}

return true;
}

function validateComments(fld) {
var error = "";
if (fld.value == "") {
fld.style.background = '#339933';
error = "Please enter a message.\n";
} else {
fld.style.background = 'White';
}
return error;
}

Also having the same problem with this cursor position script having no effect:

----from validate.js------------------

function setSelRange(inputEl, selStart, selEnd) {
if (inputEl.setSelectionRange) {
inputEl.focus();
inputEl.setSelectionRange(selStart, selEnd);
} else if (inputEl.createTextRange) {
var range = inputEl.createTextRange();
range.collapse(true);
range.moveEnd('character', selEnd);
range.moveStart('character', selStart);
range.select();
}
}

setSelRange(document.contact.commments, 0, 0)

Fotiman

2:23 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



One problem that I see (though I don't know if it's the cause of the problem you are experiencing) is that you have an input field named "name", and you attempt to access that field via the form:
reason += validateName(contact.name);

The problem with this is that the form element has a "name" attribute, so you might be passing in that attribute instead of the input element. It's possible then that your validation function tries to access a property that doesn't exist, and so it simply quits. For example, here:

if (fld.value == "") {

That is assuming that fld is an input element, but if it is the form's name attribute, then trying to access fld.value will throw an error. I would start by renaming your input element and see if that is the cause of the problem.

jpolsonb

2:28 pm on Nov 4, 2009 (gmt 0)

10+ Year Member



ok i have stripped it down to the following code. It really cant get much simpler but I have tried all I can think of. The java script works for inputs but not textarea and I simply dont understand why?

html-----------------------------------------
<head>
<script type= "text/javascript" language="JavaScript" src="validate3.js"></script>
</head>
<body>
<form name="contact" action="maile.php" method="post" onsubmit="return validateFormOnSubmit(this)">
<fieldset>
<ol>
<li>
<textarea name="textbox" rows="8" cols="45" id="textbox">
</textarea>
</li>
</ol>
<p><input type="submit" name="Submit" value="Send" style="cursor:pointer"/></p>
</fieldset>
</form>
</body>

validate3.js---------------------------------------

function setSelRange(inputEl, selStart, selEnd) {
if (inputEl.setSelectionRange) {
inputEl.focus();
inputEl.setSelectionRange(selStart, selEnd);
} else if (inputEl.createtextRange) {
var range = inputEl.createtextRange();
range.collapse(true);
range.moveEnd('character', selEnd);
range.moveStart('character', selStart);
range.select();
}
}

setSelRange(document.theForm.textbox, 0, 0)

function validateFormOnSubmit(theForm) {
var reason = "";

reason += validateTextBox(theForm.textbox);


if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}

return true;
}

function validateEmpty(fld) {
var error = "";

if (fld.value.length == 0) {
fld.style.background = '#339933';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}

function validateTextBox(fld){
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores

if (fld.value == "") {
fld.style.background = '#99ff99';
error = "Please enter a message.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = '#99ff99';
error = "The message contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}

function trim(s)
{
return s.replace(/^\s+¦\s+$/, '');
}

Fotiman

2:36 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I just tried that example, and it worked for me. Note, though, that there is an error. Your script tries to do this:

setSelRange(document.theForm.textbox, 0, 0)

before the document has loaded, so document.theForm does not exist and it errors.

If you haven't already, I would recommend installing Firefox and the Firebug plugin. It has a great JavaScript debugger.

But otherwise, when I clicked the submit button the field turned green and I saw an alert message and the form did not submit.

jpolsonb

2:52 pm on Nov 4, 2009 (gmt 0)

10+ Year Member



i will get the fire bug plugin now.

even though there is an error message it sayss there are illegal characters when there are none in the field. It should see there are no characters and display the corresponding message.

Thanks for the info on setSelRange issue its a new lead for me to follow. Where and how would you advise me to include it?

Was the error message you got the illegal character one?

Fotiman

3:09 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I tried the code example, and when the field was empty I saw:
"The message contains illegal characters."
Looking closely, I see that it's because the textarea actually has a newline in it because I've put the closing </textarea> on a new line instead of immediately after the opening <textarea>. So you should remove that newline, or better yet, trim the value of leading and trailing whitespace.

jpolsonb

3:31 pm on Nov 4, 2009 (gmt 0)

10+ Year Member



ok thats another great tip, i didnt realise having the closing <textarea> tag on another line would have an impact. Ive literally spent hours tring to solve these two small problems.

I have tried putting setSelRange(document.theForm.textbox, 0, 0) in the head of the document containing the form like this:

<head>
<script type= "text/javascript" language="JavaScript" src="validate3.js">setSelRange(document.theForm.textbox, 0, 0)</script>
</head>

It seems to be working, is that where you would put it?

I'm really so grateful for your help.

Fotiman

3:46 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



That will fail in the head because document.theForm does not exist. Note also, you can't have a script that has both a src attribute AND inline script code (the inline script code will be ignored).

You could either move the call to setSelRange to the end of your document (script tags are generally best placed before the closing </body> tag), and/or you could attach an event listener to execute the script when the DOM is ready or on window load.

jpolsonb

3:54 pm on Nov 4, 2009 (gmt 0)

10+ Year Member



how about:

window.onload=function(){
setSelRange(document.theForm.textbox, 0, 0);
}

in my validate.js file?

this seems to be working.

Fotiman

4:06 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



That should work. One issue that could arise from that, though, is that if you ever include another script that also sets window.onload. Whichever one is defined last will win. Or if you set your body onload event handler, you'll also have a problem. window.onload is the best approach (in my opinion) if you have total control over your pages and you don't want to get into Event Listeners. However, a better approach would be to assign an event listener (multiple listeners can be assigned to an event). Unfortunately, there is not a standard cross-browser implementation, so this often requires writing your own addEvent method, or using one of the JavaScript frameworks like the Yahoo UI Library, jQuery, etc.

Here's an example using the Yahoo UI Library:


<script type="text/javascript" src="http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function () {
setSelRange(document.theForm.textbox, 0, 0);
});
</script>

Note, that uses onDOMReady (which is slightly sooner than the window onload event).

Fotiman

4:07 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Note, though, that the overhead of including a framework like Yahoo UI Library might not be worth it for a single event listener. :)

jpolsonb

4:11 pm on Nov 4, 2009 (gmt 0)

10+ Year Member



Great thanks i will look into javascript frameworks a little more in the tweaking phase, thanks for all the advice. New to java script but worked a little with php and action script so ill get there eventually.

Appreciate your time.

Regards,

Jamie Brown