Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic Form Validation Not Working 1

Status
Not open for further replies.

PCHomepage

Programmer
Feb 24, 2009
609
US
I use this code on several sites but it seems to be resisting my efforts to add it to a new one. When I submit the empty form as a test, all fields except EMail highlight in yellow but for only a second or two, then the form submits. There is no alert and no yellow on the EMail field. It's not a problem with pop-up blockers since, as mentioned, I use it on other sites on this same system and browser. Any ideas?

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

  reason += validateEmpty(theForm.Name);
  reason += validateEmpty(theForm.Message);
  reason += validateEmpty(theForm.SecurityCode);
  reason += validateEmail(theForm.EMail);

  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 = 'Yellow';
        error = "Required field(s) missing.\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 = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

The form itself is part of a PHP function but again, it's little different than I use elsewhere.

HTML:
<form method="POST" onsubmit="return validateFormOnSubmit(this)" name="SendMessage" action="/?ID=3">
	<fieldset>
		<p><label for="Name">Your Name</label>
			<input name="Name" type="text" size="25" value="<?=$Name?>" id="Name"></p>
		<p><label for="EMail">Your Email</label>
			<input name="EMail" type="text" size="25" value="<?=$EMail?>" id="EMail"></p>
		<p><label for="Message">Message</label>
			<textarea name="Message" rows="5" cols="65" id="Message"><?=$Message?></textarea></p>
		<p><label for="SecurityCode">Security Code</label> 
		<img src="/quickcaptcha/imagebuilder.php" border="1">&nbsp; <strong>Enter code as shown</strong>&nbsp; <input name="VerifyCode" value=""></p>
		<p><input name="Contact" type="submit" value="Send Message"></p>
	</fieldset>
</form>
 
You should "break" at every error condition otherwise you will only 'catch' one error message.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
I am a programmer but not a JavaScript programmer so this is borrowed code that works exactly as it is on my other sites. Anyway, I tried adding [bold]break;[/bold] as suggested but then it gave no yellow at all, not even for an instant.
 
Sure but you need to 'break' and return that value to the calling routine, otherwise each time it encounters a different error condition [if more than one exists] it will only return the last known error condition to the user, when in actual fact you want to highlight and teturn all the error conditions.



Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
One error that maybe throwing a wrench in the workings is you have no field called "SecurityCode., your captcha input is called VerifyCode.

When your code tries to check for that it issues an error because the fld variable is empty, so your js stops running and never reaches the end to return a false to stop the form from submitting.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
That was it, thank you! I was mixing up the session name of another site with the form field name here.
 
I am using this code to check if the Captcha has been filled but the validation itself is being done using PHP. Can it be done as part of this JavaScript? I tried creating a function but it does not seem to be working.

JavaScript:
function validateCaptcha(fld) {
	var postData = $("form").serialize();
	var requestUrl = '/functions/validate.php';
         $.ajax({
             type: "POST",
             dataType: "json",
             data: postData,
             url: requestUrl,
             success:function(data) {
		fld.style.background = 'Yellow';
		error = "The codes do not match.\n";
             }
         });
    return error;
}

validate.php contains:

PHP:
<?php
if (isset($_POST['VerifyCode']) && strcasecmp($_SESSION['string']) != $_POST['VerifyCode']) :
	return 0;
else :
	return 1;
endif;
exit;
?>
 
It comes down to where you store the code to check against. I'm sure it could be done if you store the current code in an element the JS can access.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
It's stored as a session value, which is why the php script to check its validity. However, I'm not sure how to apply it to the JavaScript so what I posted was simply a very rough draft.
 
You can echo it out to a hidden input or as a data value of any element you want, and then check against that using JS.

i.e.:

Code:
<input type="hidden" name="securityCode" value="<?php echo $_SESSION['string'];">






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
The Capcha is currently working just fine on the PHP side but I want to check it in JavaScript if enabled. I am not sure how to get the a server side session value in a client side programming language. The JavaScript us in an external .js file.
 
Like I said above, Assuming your session variable gets set when the page is requested, just echo it out to the page, and use Js to get the value.

Or simply have your Ajax request return the actual value of the captcha instead of a 0 or 1.








----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Yes I understand that but in a .js script, I can't run PHP. I tried but nothing happens and having the PHP there seems to kill the whole script.
 
I tried but nothing happens and having the PHP there seems to kill the whole script.

As it would.


PHP is over and done with before javascript even get delivered to the browser never mind starts running.

You PHP remains in .php files on the server and your javascript has to request the values from the server.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
ChrisHirst said:
PHP is over and done with before javascript even get delivered to the browser never mind starts running.
You PHP remains in .php files on the server and your javascript has to request the values from the server.

Yes, but again, if you echo the session var while PHP is running, there should be a value output to the HTML that Js can then access.


@PCHomePage
Missed the closing PHP tag before.
Code:
<input type="hidden" name="securityCode" value="<?php echo $_SESSION['string'];[COLOR=#A40000][b]?>[/b][/color]">


If you look at the delivered HTML code when your page loads having added the PHP, the element should show the value that was echoed out.


This of course is assuming the page your form is on is a PHP page where you have indeed set the session var originally.

PHP:
<?php
$_SESSION['string'] == "captcha value";
?>

<input type="text" name="captchaValue" value="<?php echo $_SESSION['string'];?>">

This should give you a text box with the captcha value that is stored in the session variable. From there you can use JS to access the value that was set previously.

Where exactly is the point you are getting hung up? Or what about this process don't you understand specifically? Echoing out a value form PHP will print it to the HTML. From there Js can access it. Yes it will be a static value since it was echoed from PHP.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top