Javascript Validation

I have my form validation working, but when I test it by leaving a required filed blank, it still sends the email. Not too sure where I missed up, because my error console hasnt picked up any errors.



<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact</title>
<link href="style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
function ValidateContactForm()
{
if (document.getElementById("text").value === "") 
{
	window.alert("Please provide a detailed description or comment.");
	document.getElementById("text").focus();
	}
if (document.getElementById("author").value === "")
{
	window.alert("Please provide your name.");
	document.getElementById("author").focus();
}
if (document.getElementById("verif_box").value === "")
{
	window.alert("Please enter captcha code.");
	document.getElementById("verif_box").focus();
}

if 

(!(/^([a-z0-9])([\\w\\.\\-\\+])+([a-z0-9])\\@(([\\w\\-]?)+\\.)+([a-z]{2,4})$/i.test(emailAddress.val

ue))) {
	window.alert("Please enter a valid email address.");
	document.getElementById("email").focus();
}
return false;
}

</script>
</head>
<body>



so where is the variable email defined then in your updated code and which is line 29?

I have it defined as email, I now went ahead and changed it, but I get the error (Expected ‘(’, line 29, char 1).


<script type="text/javascript">
function ValidateContactForm()
{
if (document.getElementById("text").value === "") 
{
	window.alert("Please provide a detailed description or comment.");
	document.getElementById("text").focus();
	}
if (document.getElementById("author").value === "")
{
	window.alert("Please provide your name.");
	document.getElementById("author").focus();
}
if (document.getElementById("verif_box").value === "")
{
	window.alert("Please enter captcha code.");
	document.getElementById("verif_box").focus();
}

if 

(!(/^([a-z0-9])([\\w\\.\\-\\+])+([a-z0-9])\\@(([\\w\\-]?)+\\.)+([a-z]{2,4})$/i.test(email.val

ue))) {
	window.alert("Please enter a valid email address.");
	document.getElementById("email").focus();
}
return false;
}



where is emailAddress defined in your code?

Why is the JavaScript in the head of the web page rather than immediately before the body tag? In the head it just slows the loading of the web page and also overly complicates the JavaScript as it then has to wait for all the things in the page to load that it told to wait until it finished loading first before it can run. With the script at the bottom you know that everything it needs to access in the page has already loaded and so can get rid of the onload.

You should get the web page working first without the JavaScript and make sure all the server side validation is working as that is what you are relying on to validate what your visitors enter. The JavaScript to make it easier for them to spot errors can be added once you know everything else works.

=== is a valid Javascript comparison operator. It checks if two things are the same type, e.g. (“3” === “3”) is true, and (“3” == 3) is true, however (“3” === 3) is false.

You really need some PHP validation in there too. Javascript can be turned off, modified by a user (via the address bar or many dev tools e.g. firebug) completely removing the use of your Javascript validation.

There is a distinction that needs to be made here. Javascript is good for making things more ‘interactive’ and making processes easier for users. However, for real validation you want PHP to do that. It should go to at least the extent of the checks that Javascript is doing.


//First you need to make sure the form is sent and everything is there.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //Was everything sent? (it should have been, even empty fields)
    if(!isset($_POST['name'], $_POST['email'], $_POST['subject'], $_POST['message'])){
        echo '<b>Form error</b> - Not everything was sent in the form. Was the HTML correct?';
    }else{
        //Set the variables to the form values
        $first_name=$_POST['name'];
        $email_address=$_POST['email'];
        $subject=$_POST['subject'];
        $message=$_POST['text'];
        /*
         * If their lengths are zero, output an error.
         * 
         * There are better, cleaner ways of going through
         * each one, but I'm guessing PHP isn't a strength
         * and therefore it's better to be simple with the code.
         * 
         */
        if(strlen($first_name) == 0){
            echo '<p><b>Empty Field</b> - First Name</p>';
        }else if(strlen($email_address) == 0){
            echo '<p><b>Empty Field</b> - Email Address</p>';
        }else if(strlen($subject) == 0){
            echo '<p><b>Empty Field</b> - Subject</p>';
        }else if(strlen($message) == 0){
            echo '<p><b>Empty Field</b> - Message</p>';
        }else{
            $Sent = mail("--your--email--address--","Subject: {$subject}", $message, "From: $first_name <{$email_address}>");
            if($Sent){
                echo 'Success! :D';
            }else{
                echo 'Aww it failed :(';
            }
        }
    }
}
?>

I’ve removed your email address from the code. You will want to do that too. Exposing your email address online isn’t a great idea - spambots can scan sitepoint (and any other websites) at any point collecting email addresses. If you can’t edit your initial post with the email address, ask a moderator to do so.

hoku 2000
Not an expert but my guess is you have to have return set to all the ifs before the final if declares true. That is the only thing I see missing in your script.
EG.


function whatever(){
var 1=blah;
var 2=blah blah;
if(1.value==' '){
//jump up and down
return false;//missing
}
if(2.value==' '){
//jump up and down some more
return false;//missing
}
else{
//don't jump up and down
return true;
}}

Something like that, also watch your comparison operators ‘=’ outside of ‘if’ and ‘==’ inside of ‘if’.:sick:

I am guessing it might be also that too. I’ve also got another onSubmit () that needs to go on my form.

Where is the line that calls your checkEmail() function?

Also, your html is invalid with mis-matched </div> tags. The w3c validator will help you fix your html.

The order I would suggest in fixing up your code is.

1- fix the html until it passes validation on the w3c validator

2- get the javascript validation working correctly

3- then worry about the php code to send the email.

I wouldn’t recommend putting a return in each IF block because if there is more than 1 invalid input, an alert would pop up after only the first invalid input is found.

A more user friendly way is to display all the errors in one go by validating each input and if the input is invalid store an appropriate error message in an array. Then after all inputs have been validated, display the contents of the error message array (if there were errors) and return false to abort the submit event. If no errors occurred, then return true.

Also, there are other things missing - see post 7

Now I did somethings different. When I leave the email portion blank, nothing happens when I am suppose to have an alert box show up. And even when I put in a valid email address, it doesnt send. :confused:



<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact</title>
<link href="style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
function ValidateContactForm()
{
if (document.getElementById("text").value === "") 
{
	window.alert("Please provide a detailed description or comment.");
	document.getElementById("text").focus();
	}
if (document.getElementById("author").value === "")
{
	window.alert("Please provide your name.");
	document.getElementById("author").focus();
}
if (document.getElementById("verif_box").value === "")
{
	window.alert("Please enter captcha code.");
	document.getElementById("verif_box").focus();
}  
function checkEmail() 
{
var email = document.getElementById("email");
var filter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) 
{
alert('Please provide a valid email address');
email.focus;
}
return true; // successful
  }
  return false; // failed validation
}

</script>
</head>
<body>

<div id="templatemo_wrapper"> 

	<div id="templatemo_header">

 
        
        <ul id="social_box">
                    <li><a href="http://www.facebook.com/"><img 

src="http://www.sitepoint.com/forums/images/facebook.png" alt="facebook" /></a></li>
            <li><a href="http://www.twitter.com/"><img src="http://www.sitepoint.com/forums/images/twitter.png" 

alt="twitter" /></a></li>              
        </ul>
        
      	<div id="site_title">
            <h1><a href="index.htm"><img src="http://www.sitepoint.com/forums/images/logo2.png" alt="logo" 

/><span></span></a></h1>
        </div> <!-- end of site_title -->
        
      
    </div> <!-- end of templatemo_header -->
    

<!-- end of templatemo_menu -->
    
    <div id="templatemo_content_wrapper">
    	<div id="templatemo_content_top"></div>
        <div id="templatemo_content">
        
            <h2>Contact</h2>



<p><b>E-mail: starr05@gmail.com </b></p>

<p><b><a href="http://www.twitter.com/">Twitter</a></b></p>
        
            <div class="cleaner_h50"></div>
            
            	<div id="contact_form">
            
                    <h4>Quick Contact</h4>
                    
                    <form method="post" name="ContactForm" id="contact" action="email.php" 

onsubmit="return ValidateContactForm();">
                        
                        <div class="col_w340 float_l">
                        
                            <label for="author">Name (* Required):</label> <input 

name="author" type="text" class="input_field" id="author" maxlength="40" />
                          	<div class="cleaner_h10"></div>

 <label for="subject">Subject:</label> <input name="subject" type="text" class="input_field" 

id="subject" maxlength="40" />
                          	<div class="cleaner_h10"></div>

                            
                            <label for="email">Email (* Required):</label> <input 

name="email" type="text" class="input_field" id="email" maxlength="40" />
                          	<div class="cleaner_h10"></div>
                            
                            
Type verification image:<br />
<input name="verif_box" type="text" id="verif_box" style="padding:2px; border:1px solid 

#CCCCCC; width:180px; height:14px;font-family:Verdana, Arial, Helvetica, sans-serif; 

font-size:11px;"/>
<img src="verificationimage.php?<?php echo rand(0,9999);?>" alt="verification image, type it 

in the box" width="50" height="24" align="absbottom" /><br />
<br />                        

</div>
                        


                        <div class="col_w340 float_r">
                        
                            <label for="text">Message (*Required):</label> <textarea 

id="text" name="text" rows="0" cols="0" class="required"></textarea>
                            <div class="cleaner_h10"></div>
                            
                            <input type="submit" class="submit_btn float_l" name="submit" 

id="submit" value="Send" />
                            <input type="reset" class="submit_btn float_r" name="reset" 

id="reset" value="Reset" />
                            
                        </div>
                        
                   </form>

            </div> 

            <div class="cleaner"></div>
            
        </div>
        <div id="templatemo_content_bottom"></div>
	</div>
    
    <div id="templatemo_sp_box">
    
    	<div class="col_w340 float_l">
         
			</div>
        </div>
        
        <div class="col_w340 float_r">
        
			</div>
        </div>
    
    </div>
    
    <div id="templatemo_footer">

      
        Copyright © 2011 <a href="www.twitter.com/">Starr</a><br/> 
        <a href="http://www.iwebsitetemplate.com" target="_parent">Website Templates</a> 
        by <a href="http://www.templatemo.com" target="_parent">Free CSS Templates</a>
    
    </div> <!-- end of templatemo_footer -->
    
</div> <!-- end of templatemo_wrapper -->    

</body>
</html>







<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>


<?php


$first_name=$_POST['name'];
$email_address=$_POST['email'];
$subject=$_POST['subject'];
$message=$_POST['text'];

mail("starr05@gmail.com","Subject: $subject",
$message, "From: $first_name <$email_address>");

echo "Thank you for using our mail form.<br/>";
echo "Your email has been sent.";
?>




</body>
</html>



Line 29 is where the IF statement for the email starts. When I define email would I define it like var email =ContactForm.email?

Try the link bellow and you will get a lot less headache:

Creating a Facebook-like Registration Form with jQuery | Tutorialzine

How you display the form is a matter of choice dependent on whether you need to support browsers with javascript not available.

But the bottom line is that if data security and data integrity are an issue then server side validation must be done and client side validation (javascript) is optional because it can be very easily bypassed.

Would I have to change it to validateContactForm instead?

hocku 2000 I see you are referencing a function not in the script at all with your body onload, surly startform would have to be in the script tags for you to call it on load? It’s not there?

Still getting an error on line 43 (where I have my <body onLoad=“startForm”>)

Yeah hocku I think the javascript part has the return statements reversed, should be return false first followed by return true if the errors aren’t there. I guess that is why you used ‘===’ in the ifs which might reverse the return statements. What blows my mind is that the form will get posted to the server anyway, errors and all. The only way I know that is that IE8 throws a confirm message to allow you to send or stop the form action mailto regardless of errors or not! If the form action was not mailto you would never know the form had been posted.

hoku_2000 and Jake and webdev1985 I now fetch my forms with an object technique that loads the form to the div I want. The beauty of this is that the object html is not revealed in the source code. Well not in IE8 anyway. As far as I know the Javascript in the object can not be referenced by external link and has to be within script tags of the html page contained in the object preferably before the clossing body tags??? Don’t think a hacker could access the object inner html but would like to know the answer.

The truth is I don’t want to post any form to the server with errors so I would like to change the form action or methode with the onsubmit in javascript with validation check function that will stop posting to the server if the form isn’t filled out right Period! I guess a forms inner html could be re written to achieve that affect. Not sure??:shifty:

Something like my previous post where I change the form action value or method or the entire form inner html. This would of course be extreamly dangerous if the hacker could access the inner html of the object?

Your input field is named ‘text’ but both the Javascript and the PHP were asking for ‘message’. Change the HTML field name and all should be well :slight_smile:

Removing the Javascript entirely, it wasn’t necessary. Javascript validation is a useful thing, because it offers a fast response to the user. Its just a case of not relying on it; Code your PHP like there is no Javascript validation at all. THEN code your Javascript validation as if the PHP validation wasn’t there (forgetting the many ways of bypassing it). That way you have a form that’s useful to users who aren’t trying to beat the system, and enough security on the back end to prevent users from beating the system if they’re so inclined :slight_smile:

As for changing the message… Try and figure it out. I’m sure you’ll do it :slight_smile: