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>
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;
}
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 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.
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.
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.
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?
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 Jakeand 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??
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
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
As for changing the message… Try and figure it out. I’m sure you’ll do it