INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Basic Form Validation Not Working

Basic Form Validation Not Working

(OP)
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?

CODE --> 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.

CODE --> 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">  <strong>Enter code as shown</strong>  <input name="VerifyCode" value=""></p>
		<p><input name="Contact" type="submit" value="Send Message"></p>
	</fieldset>
</form> 

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

(OP)
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 break; as suggested but then it gave no yellow at all, not even for an instant.

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

(OP)
That was it, thank you! I was mixing up the session name of another site with the form field name here.

RE: Basic Form Validation Not Working

(OP)
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.

CODE --> 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:

CODE --> PHP

<?php
if (isset($_POST['VerifyCode']) && strcasecmp($_SESSION['string']) != $_POST['VerifyCode']) :
	return 0;
else :
	return 1;
endif;
exit;
?> 

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

(OP)
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.

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

(OP)
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.

RE: Basic Form Validation Not Working

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

RE: Basic Form Validation Not Working

(OP)
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.

RE: Basic Form Validation Not Working

Quote:

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

RE: Basic Form Validation Not Working

Quote (ChrisHirst)


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'];?>"> 


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.

CODE --> 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

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close