JavaScript - Form Validation: Email, Needs To Be .com, .org, Or .net
I am having trouble with my Contact Us form. For the validation for email, in function validateEmail in my javascript portion where if I include:
Code: else if (fld.value(".com")==-1 && entEmail.indexOf(".net")==-1 && entEmail.indexOf(".org")==-1 && entEmail.indexOf(".edu")==-1) { window.alert("Please recheck your email address. it must in name@domain.xxx format."); return false; } It skips the validation when I click the submit button and sends without validating the form. When I remove the code snippet above it validates fine but doesn't check for ".com", ."org", or ."net" which has to be included. I need to include a proper email address that includes "@" AND either one of these: ".com", ."org", or ."net" Anyone know of any ideas to solve this? Similar TutorialsHi, I have a simple bit of HTML / Javascript to validate email addresses entered into a field, split by a comma. Code: <html> <body> <form name="myForm" onsubmit="return chkEmail()" method="post"> e: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </body> </html> Code: function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function chkEmail(){ var myString = document.forms["myForm"]["fname"].value; var mySplitResult = myString.split(","); for(i = 0; i < mySplitResult.length; i++){ emailCheck = validateEmail(mySplitResult[i]); alert(mySplitResult[i] + " - " + emailCheck); if (emailCheck = 'false') { alert(emailCheck); } } } If I enter e.g. "you@me.com,this@that.com" into the form, the alert debugs show: First: you@me.com - true Second: false Third: this@that.com - true Fourth: false The first debug seems to show that the condition is true, but then the if statement to check for a "false" value is firing, showing the value of "emailCheck" = "false", even though on the preceding alert, the value = "true". I'm not sure what's going wrong. Apologies for any silly mistakes. I also put my code he http://jsfiddle.net/XYyZa/ Thanks I have been modifying this form: http://www.kartaway.com.au/form.html to be part of an iPhone optimized site for the same client. The modified form works, however it no longer stops emails being sent that do not have the required fields filled in. The modified form is he http://marketingandbranding.com.au/itest/icontact.html The original is built using a table which I have removed and replaced with divs. Didn't think I'd left anything out which would matter but I guess I must have. Please help, i don't really know any JavaScript except what I copy and paste. I am a javascript begginer and would like to know what is this bit of code saying? (email.indexOf("@",atPos+1) > -1) Thank you! Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Email checker</title> <script type="text/javascript"> function validEmail(email) { invalidChars = " /:,;" if (email == "") { return false; } for (i=0; i<invalidChars.length; i++) { badChar = invalidChars.charAt(i) if (email.indexOf(badChar,0) > -1) { return false; } } atPos = email.indexOf("@",1) if (atPos == -1) { return false; } if (email.indexOf("@",atPos+1) > -1) { return false } periodPos = email.indexOf(".",atPos) if (periodPos == -1) { return false; } return true; } function submitIt(emailForm) { if (!validEmail(emailForm.emailAddr.value)) { alert("Invalid email address"); emailForm.emailAddr.focus(); emailForm.emailAddr.select(); return false } alert("email is correct!"); return true; } </script> </head> <body> <h2>Email checker</h2> <form onsubmit="return submitIt(this)" action="#"> Email Address: <input name="emailAddr" type="text" size="30" /> <p><input type="submit" value="Submit" /> <input type="reset" /></p> </form> </body> </html> Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript or how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. It'd be great if the submit button could be disabled until all fields are filled correctly, but I don't know if this is possible. Thanks in advance, and please let me know if it'll be possible. :) Hi Everyone! I have a text box ... but the label is in the textbox as the value so I use this code to make sure that something is filled in the field when a user clicks send: if(form.email.value == ('' || 'email*')){ alert('Please enter your email address'); return false; } <label><input type="text" name="email" id="email" class="required" value="email*" onfocus="if( this.value == 'email*') {this.value = '';}" onblur="if (this.value == '') { this.value = 'email*';}" /></label> I have tried to add email validation to the javascript code but I am failing! can someone help please? at the moment it just checks to see if the field has been filled out but doesn't check for the @ and .co.uk or .com. Many thanks! Let's start by saying that I stink at javascript. I've taken multiple different tutorials, some more than once, and I still can't get it. So, when I need a code, I search for it, and try different ones until I find something that works. I've been looking for a code for email validation for quite a long time, and I still can't find something that works with my code for validating the other parts of my contact form. I can get it to check for the presence of text, but not for the presence of an @ sign and period. I would like for someone to please help me figure this out. Right now I have the following code: Javascript Code: <!-- function validate_form ( ) { valid = true; if ( document.contact.firstnamecontact.value == "" ) { alert ( "Please fill in the 'First Name' box." ); valid = false; } if ( document.contact.lastnamecontact.value == "" ) { alert ( "Please fill in the 'Last Name' box." ); valid = false; } if ( document.contact.emailcontact.value == "" ) { alert ( "Please fill in a valid email address." ); valid = false; } if ( document.contact.subjectcontact.value == "" ) { alert ("Please fill in the 'Subject' box." ); valid = false; } if ( ( document.contact.topic[0].checked == false ) && ( document.contact.topic[1].checked == false ) && ( document.contact.topic[2].checked == false ) ) { alert ( "Please choose your Topic of Inquiry" ); valid = false; } if ( document.contact.messagecontact.value == "" ) { alert ( "Please specify a question/comment." ); valid = false; } return valid; } //--> HTML Code: <form name="contact" method="post" action="contactcompletion.php3" onsubmit="return validate_form ( );"> <table> <tr> <td><b>First Name: </td><td><input type="text" name="firstnamecontact"/></td> </tr> <tr> <td><b>Last Name: </b></td><td><input type="text" name="lastnamecontact"/></td> </tr> <tr> <td><b>Email: </b></td><td><input type="text" name="emailcontact"/></td> </tr> <tr> <td><b>Subject: </b></td><td><input type="text" name="subjectcontact"/></td> </tr> </table> <br /> <br /> <h4>Topic of Inquiry (Choose One):</h4> <table> <tr> <td><input type="radio" name="topic" value="questionscontact" /><b> Questions</b></td> <td><input type="radio" name="topic" value="commentscontact" /><b> Comments</b></td> <td><input type="radio" name="topic" value="othercontact" /><b> Other</b></td> </tr> </table> <br /> <br /> <h4>Enter Your Questions or Comments:</h4> <br /> <textarea name="messagecontact" rows="10" cols="70"></textarea> <br /> <br /> <p><input type="submit" name="send" value="Send" /></p> Thanks a bunch in advance for helping me!! I've got a form validation script and I'm trying to add in a little extra oomph to what it checks. I'm not sure on the syntax for this, but I'm currently trying to make sure the email has the proper data using something like: else if (email.indexOf("@")<1 || email.indexOf(".")==-1 || email.indexOf(",")!=-1 || email.indexOf(" ")!=-1 || email.length<6) But when I add that if statement, the script does nothing, and they're taken to the next page. While I'm at it, is it possible to make sure that at least one of a series of looped-in dropdowns that have a php generated name: <select name="participantqty[<?= $c_row['workshop_id'] ?>]" id="" class=""> Here's the script I'm working from, with my if statement in it and breaking things: Code: <script type="text/javascript"> function required(){ var first = document.forms["register1"].elements["fname"].value; var last = document.forms["register1"].elements["lname"].value; var email = document.forms["register1"].elements["email"].value; var message = document.forms["register1"].elements["phone"].value; if(first == null || first == "" || last == null || last == ""){ alert("First and last name fields are required."); return false; } else if(email == null || email == ""){ alert('An email address is required.'); return false; } else if (email.indexOf("@")<1 || email.indexOf(".")==-1 || email.indexOf(",")!=-1 || email.indexOf(" ")!=-1 || email.length<6) { alert('Please enter a valid E-mail address.\n" + "Example: myname@domainname.com"); register1.email.focus(); return false; } else if(message == null || message == ""){ alert('A phone number is required.'); return false; }else{return true;} } </script> This piece of Dreamweaver(?) code appears to validate an email address: Code: function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } The checking routine works well except I can't figure out how to invoke the email check part (red above?). This is the onsubmit bit: Code: <form id="quoteform" name="contactfrm" onsubmit="MM_validateForm('First_Name','','R','Last_Name','','R','City','','R','State','','R','Zip','','R','Day_Phone','','R','Evening_Phone','','','Email','','R');return document.MM_returnValue;" action="contact.php" method="post"> I have tried altering the field id and name below to "isEmail' but it does nothing: Code: <td height="32" bgcolor="#F8F8F8"><strong>Email Address:</td> <td><input name="YOUR EMAIL" type="text" id="Email" size="30"></td> Is it obvious? I was hoping you could point out why the validation for the email in the script below keeps looping and how to fix it. Any pointers would be great. Thank you. Script is being used on a Static FBML page. Code: <script type="text/javascript"> function checkForm() { var params=document.getElementById('myForm').serialize(); if(params.fullname==''){ displayerrormessage('Please Enter Your Full Name'); return false; } if(params.useremail==''){ displayerrormessage('Please Enter Your Email'); return false; } if(params.useremail!=''){ var emailfilter=/^w+[+.w-]*@([w-]+.)*w+[w-]*.([a-z]{2,4}|d+)$/i var returnval=emailfilter.test(params.useremail); if (returnval==false){ displayerrormessage('Please Enter Valid Email'); params.useremail.select(); } return false; } if(params.userphone==''){ displayerrormessage('Please Enter Your Phone'); return false; } if(params.usercity==''){ displayerrormessage('Please Enter Your City'); return false; } if(params.userstate==''){ displayerrormessage('Please Enter Your State'); return false; } if(params.usercountry==''){ displayerrormessage('Please Enter Your Country'); return false; } if(params.CompanyOrganization==''){ displayerrormessage('Please Enter Your Company/Organization'); return false; } if(params.TitlePostion==''){ displayerrormessage('Please Enter Your Title/Postion'); return false; } if(params.Message==''){ displayerrormessage('Please Enter Your Message'); return false; } } function displayerrormessage(message){ new Dialog().showMessage('Erro Message',message); return false; } </script> <script type="text/javascript"> var emailfilter=/^w+[+.w-]*@([w-]+.)*w+[w-]*.([a-z]{2,4}|d+)$/i function checkmail(e){ var returnval=emailfilter.test(e.value); if (returnval==true){ alert('Please enter a valid email address.') e.select() } return true; } </script> <form id="myForm"> <p>Full Name : <input type="text" name="fullname" id="fullname"/> </p> <p>Email : <input type="text" name="useremail" id="useremail"/> </p> <p>Phone : <input type="text" name="userphone" id="userphone"/> </p> <p>City : <input type="text" name="usercity" id="usercity"/> </p> <p>State : <input type="text" name="userstate" id="userstate"/> </p> <p>Country : <input type="text" name="usercountry" id="usercountry"/> </p> <p>Company/Organization : <input type="text" name="CompanyOrganization" id="CompanyOrganization"/> </p> <p>Title/Postion : <input type="text" name="TitlePostion" id="TitlePostion"/> </p> <p>Your Message : <input type="text" name="Message" id="Message"/> </p> <input type="button" name="nameuser1" id="nameuser1" onclick="checkForm();" value="Submit"/> </form> This are my codes.. var add = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var email = form.txtEmail.value; if (add.test(email) = false) { alert("Please enter a valid email."); return false; } return true; } bt it wun work.. pls help.. Hey, basically I have my assignment due in 2 and a half hours and I cannot work out how to validate a email address. What am I doing wrong? Been on the net for a couple of hours lurking to find some answers but now I am even more lost. Bit of information: Basically I need to work out how many tables are needed for a class room depending on the desktops and laptops used and how many roils of coils are needed blah blah blah. Then comes the tricky part (for me anyways) asking the user to confirm or cancel the order everything works up to confirming the quote and then validating the email address, canceling the confirm button works so I'm assuming it's just the validating that I have destroyed. Any help would be awesome, assignment is due very soon and no sections of code are helping me on the net. Code: function confirmquote() { var answer=confirm("Do you want to recieve a quote?"); if (answer==true) { var emailID=window.prompt("Please enter a VALID email address or type quit to exit"); } else { alert("Quote has been rejected sir, please refreash to start order agian."); } } } function CheckEmail() { emailID = document.f1.Email.value AtPos = emailID.indexOf("@") StopPos = emailID.lastIndexOf(".") Message = "" if (emailID == "") { Message = "Not a valid Email address" + "\n" } if (AtPos == -1 || StopPos == -1) { Message = "Not a valid email address" } if (StopPos < AtPos) { Message = "Not a valid email address" } if (StopPos - AtPos == 1) { Message = "Not a valid email address" } return Message } (ALL IN THE HEADER TAG) Code: var worknowplease = confirmquote(); var emailID=checkemail(); (Last few lines of code before [/body]) I have no idea what the validate email is trying to do in the coding, but I'm still very freash on JS. Thanks you for reading and if you can share any possible solutions to my problems. Thanks agian. I can't seem to get any Email validation to work, at all. no matter what different tactic I try. Right now I'm trying the most simplest of tactics.. Code: if((document.subscribe.contacttype.selectedIndex==1) && (document.subscribe.email.value=="")){ alert("Please enter a Valid Email Address."); return false; } else{ if((document.subscribe.email.indexOf('@') < 0) || ((document.subscribe.email.charAt(email.length-4) != '.') && (document.subscribe.email.charAt(email.length-3) != '.'))) {alert("you have entered an invalid Email Address. Please try again."); } } } Any suggestions? my 'Email' feed is displayed after the 'drop-down selector' has been chosen, thus, the invoking of the if selectedIndex==1 && email.value="" return false;. Thanks for your assistance ahead of time. Hello, When I have email validation and captcha in the same form, simply passing the captcha allows the form to be sent without an email address. When I remove the captcha, the form will not send without the email address. I want to have both. What am I missing? http://jaxpubliclibrary.org/lib/websiteform-test.html Code: <script> function validateForm() { var x=document.forms["WebsiteQuestion"]["Email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } } function clearForms() { var i; for (i = 0; (i < document.forms.length); i++) { document.forms[i].reset(); } } </script> Code: <div align="center"> <script language="javascript" src="http://www.captcha.cc/cap.js?cap_k=tocsoLPahVjmEHJZWtenaJEDoJXfrQaa" type="text/javascript"> </script> <input type=hidden name=cap_h id=cap_h value=""> <img border=1 id=cap_i src="http://www.captcha.cc/img.cgi?cap_k=tocsoLPahVjmEHJZWtenaJEDoJXfrQaa" align=middle><img align=middle style="margin-left: 4px;" id=cap_r onload="return cap_showReload(event);" src="http://www.captcha.cc/blank.png"><br> <input id=cap_t name=cap_t type=text value="" style="margin-top:4px;"> <input type=submit value="Submit Form" onclick="return cap_valid(event);"> </div> I appreciate any help. Thank you, Elbee Hi All, I am trying to create a script for checking that checks that the email address entered into two input boxes is the same when a submit button is clicked, I have these two input boxes Code: <input type="text" name="user_email" id="user_email" /> <input type="text" name="user_email2" id="user_email2" /> This javascript code Code: <script type="text/javascript"> var email1 = document.getElementById(user_email); var email2 = document.getElementById(user_email2); function checkEmail(){ if (email1 != email2) { alert("The two email addresses are not the same"); } } </script> and this code for the button Code: <input type="submit" name="submit" id="submit" onSubmit="checkEmail" /> However this code is not working, can anyone see where I am going wrong? Any help will be appreciated Thanks in advance Hello all, I am looking to add an email validation to my new user registration form. Currently, we do not validate (or activate) a new user via an activation link in the email. We don't have that process. I'd like to get my hands on the code to randonly create a security code and the actual code to sent the validation email. Can anyone help me out here? I'm absolutely new to PHP or ASP coding. I do know some HTML. Thanks
Working on college assignment, cant figure it out and need help! Basically a form that asks the user to fill in a valid email and password (ill give them the password), doesnt matter if it isnt secure, or if the email accepts dodgy emails (im just verifying the @ and a . and that is ok for the purpose of this. Anyway been trying with this code for ages now and cant see what is wrong but it isnt working, ive swapped it around and at times it does check that it is a valid email, sometimes it allows empty inputs. here is the code <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["email"].value var y=document.forms["myForm"]["password"].value var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } </script> I think i need something like && (y!="123") around the 'if' statement, but not a clue how or where it goes. Basically im going to set the password to 123 so dont have to allow for caps etc. Easiest way to do this, anyone plleeeeeaaasseee?? Kind regards Alan Hello all, new here Seems like a very nice place to be apart of. I have my website www.gebcn.com. If you view source you will see all that I have done, but more importantly my problem. I have the JS code at the top there and I am unable to W3C validate my HTML because of the JS. I am using XHTML strict and would like to stay using it. The JS I have at the top is my form validation code. I am able to do any validating that I need with this "snippet" of code, I have shrank it from my library version just to use for this newsletter. Until now W3C validating was not important now for some reason it is and I am faced with this problem. I am not a Javascript guy more of a HTML/CSS guy and I can manipulate JS to suit my needs. <problem> I have tried to make this "snippet" of JS code an external file but receive multiple errors with the JS calling for the FORM NAME as it is not on the same page. The form NAME=NEWSLETTER is another problem, as W3C says I am unable to use attribute "NAME" in this location. <problem> I would like to keep the JS close to how it is now as I have a library to use this JS over and over again. Any pointers in the right direction or solutions to my problem would be greatly appreciated. Thanks! Hopefully it is not to hard huh If there is anything anyone needs, the code pasted here, or anything else please let me know. Thanks again! Hi Guys, This isn't the first time I've posted about cookies, and I apologize for that. My cookies were working perfectly until I made some changes to the site (ie. ran it through w3 validation). Now they aren't writing. I can't find any bugs with firebug, and I've tried following it through line by line. I expect my email validation is returning false, and I would really appreciate if you can help me find the bug. Here's the code, which I call with onsubmit="return Getvalue()" The rest of the page is at www.saverally.com Code: function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return false } if (str.indexOf(at,(lat+1))!=-1){ return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ return false } if (str.indexOf(dot,(lat+2))==-1){ return false } if (str.indexOf(" ")!=-1){ return false } return true } function ValidateForm(emailID){ //var emailID=document.frmSample.txtEmail if ((emailID.value==null)||(emailID.value=="")){ showDialog('Uh-oh.','Our tech-pigeons say you must enter an email address.','success',3); emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" showDialog('Uh-oh.','Our tech-pigeons say you must enter a "proper" email address.','success',3); emailID.focus(); return false } return true } /*Email Validation*/ function Getvalue() { var validation=ValidateForm(document.getElementById("email")); if(validation==true) { user_email=document.getElementById("email").value; createCookie("userEmail",user_email,365); document.addform.submit(); return true; } else { return false; } } </script> I've literally tried everything. Read 26 tutorials, interchanged code, etc. My validation functions all work. My AJAX functions work (tested manually using servlet URL's). The second servlet validates the reCaptcha form that's generated on my webpage. After the form is validated, even if everything's correct, nothing happens upon clicking submit. I even have an alert pop up if with the captcha result, just for middle-layer debugging purposes. I want to do all of my validation clientside; none serverside. However, going to be tough if I can't get my god damn form to submit. I've been puzzled by this for close to 36 hours straight. I can't see, and I'm going to get some rest and hope that there is some useful insight on my problem when I return. html form: Code: <form id="f1" name="form1" onsubmit="validate_form(this); return false;" action="register" method="post"> <table cellspacing="5" style="border: 2px solid black;"> <tr> <td valign="top"> <table cellspacing="5"> <tr> <td>*First name</td> <td align="right"><span id="valid_one"></span></td> <td><input type="text" style="width: 320px;" id="fn" name="fn" onBlur="validate_one();"></td> </tr> <tr> <td align="left">*Last name</td> <td align="right"><span id="valid_two"></span></td> <td><input type="text" style="width: 320px;" id="ln" name="ln" onBlur="validate_two();"></td> </tr> <tr> <td align="left">*Email address</td> <td align="right"><span id="result"></span></td> <td><input type="text" style="width: 320px;" id="mailfield" name="email" onBlur="startRequest();"></td> </tr> <tr> <td align="left">*Phone number</td> <td align="right"><span id="valid_three"></span></td> <td><input type="text" style="width: 320px;" id="pn" name="pn" onBlur="validate_three();"></td> </tr> <tr> <td align="left">*City/Town</td> <td align="right"><span id="valid_four"></span></td> <td><input type="text" style="width: 320px;" id="c" name="c" onBlur="validate_four();"></td> </tr> <tr> <td></td> <td></td> <td> <select name="s"> <option value="AL">Alabama <option value="AK">Alaska <option value="AZ">Arizona <option value="AR">Arkansas <option value="CA">California <option value="CO">Colorado <option value="CT">Connecticut <option value="DE">Delaware <option value="FL">Florida <option value="GA">Georgia <option value="HI">Hawaii <option value="ID">Idaho <option value="IL">Illinois <option value="IN">Indiana <option value="IA">Iowa <option value="KS">Kansas <option value="KY">Kentucky <option value="LA">Louisiana <option value="ME">Maine <option value="MD">Maryland <option value="MA">Massachusetts <option value="MI">Michigan <option value="MN">Minnesota <option value="MS">Mississippi <option value="MO">Missouri <option value="MT">Montana <option value="NE">Nebraska <option value="NV">Nevada <option value="NH">New Hampshire <option value="NJ">New Jersey <option value="NM">New Mexico <option value="NY">New York <option value="MC">North Carolina <option value="ND">North Dakota <option value="OH">Ohio <option value="OK">Oklahoma <option value="OR">Oregon <option value="PA">Pennsylvania <option value="RI">Rhode Island <option value="SC">South Carolina <option value="SD">South Dakota <option value="TN">Tennessee <option value="TX">Texas <option value="UT">Utah <option value="VT">Vermont <option value="VA">Virginia <option value="WA">Washington <option value="WV">West Virginia <option value="WI">Wisconsin <option value="WY">Wyoming </select> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td></td> <td></td> <td><span id="error"></span></td> </tr> <tr> <td valign="top">*Anti-Spam Verification</td> <td></td> <td id="reCaptcha"></td> </tr> </table> </td> <td valign="top"> <table cellspacing="5"> <tr> <td align="left">*Affiliation</td> <td align="right"><span id="valid_five"></span></td> <td><input type="text" style="width: 320px;" id="affl" name="affl" onBlur="validate_five();"></td> </tr> <tr> <td align="left">*Research Area:</td> <td align="right"><span id="valid_six"></span></td> <td><input type="text" style="width: 320px;" id="ra" name="ra" onBlur="validate_six();"></td> </tr> <tr> <td valign="top" align="left">*Research Overview</td> <td align="right"><span id="valid_seven"></span></td> <td><textarea cols="38" rows="6" id="ro" name="ro" onKeyDown="limitText(this.form.ro,this.form.countdown,500)" onKeyUp="limitText(this.form.ro,this.form.countdown,500)" onBlur="validate_seven();"></textarea></td> </tr> <tr> <td></td> <td></td> <td><font size="1">You have <input readonly type="text" name="countdown" size="1" value="500"> characters remaining.</font></td> </tr> <tr> <td align="left">*Talk Availability</td> <td></td> <td> <input type="radio" name="ta" value="In person">In person <input type="radio" name="ta" value="Online">Online <input type="radio" name="ta" value="Both" checked>Both </td> </tr> <tr> <td align="left" valign="top">Links</td> <td></td> <td> <table id="linkTable" border="0"> <td><input type="text" style="width: 320px;" name="link"></td> <td><div id="result"></div></td> </table> </td> <td align="left" valign="top"><input type="button" value="Add Link" onclick="addLink('linkTable')"></td> </tr> <tr> <td></td> <td><span style="color: red;"></span></td> </tr> </table> </td> </tr> </table> <br /> <input type="submit" id="submit" name="submit" value="Submit Form"> </form> Javascript file: Code: /* * script.js - ajax and table functions */ var xmlHttp; // global instance of XMLHttpRequest var xmlHttp2; // second for captcha functions var validAjax = new Boolean(); var validCaptcha = new Boolean(); var valid_one = new Boolean(); var valid_two = new Boolean(); var valid_three = new Boolean(); var valid_four = new Boolean(); var valid_five = new Boolean(); var valid_six = new Boolean(); var valid_seven = new Boolean(); function init() { showRecaptcha('reCaptcha'); // Separate booleans for AJAX funcs validAjax = false; validCaptcha = false; // Booleanse for fields that don't require servlet validation valid_one = false; valid_two = false; valid_three = false; valid_four = false; valid_five = false; valid_six = false; valid_seven = false; } function showRecaptcha(element) { Recaptcha.create("6Le1a8ESAAAAAGtxX0miZ2bMg0Wymltnth7IG-Mj", element, {theme: "red", callback: Recaptcha.focus_response_field}); } function validate_form() { if (valid_one && valid_two && valid_three && valid_four && validEmail) { startCaptchaRequest(); if (validCaptcha) { return true; } } else { alert("Submission contains errors. Please fill out all required fields before submitting."); return false; } } function validate_one() { if (document.getElementById("fn").value == 0) { valid_one = false; document.getElementById("valid_one").innerHTML = "No"; } else { valid_one = true; document.getElementById("valid_one").innerHTML = ""; } } function validate_two() { if (document.getElementById("ln").value == 0) { valid_two = false; document.getElementById("valid_two").innerHTML = "No"; } else { valid_two = true; document.getElementById("valid_two").innerHTML = ""; } } function validate_three() { if (document.getElementById("pn").value == 0) { valid_three = false; document.getElementById("valid_three").innerHTML = "No"; } else { valid_three = true; document.getElementById("valid_three").innerHTML = ""; } } function validate_four() { if (document.getElementById("c").value == 0) { valid_four = false; document.getElementById("valid_four").innerHTML = "No"; } else { valid_four = true; document.getElementById("valid_four").innerHTML = ""; } } function validate_five() { if (document.getElementById("affl").value == 0) { valid_five = false; document.getElementById("valid_five").innerHTML = "No"; } else { valid_five = true; document.getElementById("valid_five").innerHTML = ""; } } // //function validate_six() { // if (document.getElementById("ra").value == 0) { // valid_six = false; // document.getElementById("valid_six").innerHTML = "No"; // } // else { // valid_six = true; // document.getElementById("valid_six").innerHTML = ""; // } //} // //function validate_seven() { // if (document.getElementById("ro").value == 0) { // valid_seven = false; // document.getElementById("valid_seven").innerHTML = "No"; // } // else { // valid_seven = true; // document.getElementById("valid_seven").innerHTML = ""; // } //} function addLink(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "text"; element1.name = "link" + rowCount; element1.style.width = "320px"; cell.appendChild(element1); } function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } function createXmlHttpRequest() { if(window.ActiveXObject) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } } function startRequest() { createXmlHttpRequest(); var param1 = document.getElementById('mailfield').value; if (param1 == "") { validEmail = false; document.getElementById("result").innerHTML = "Blank"; } else { xmlHttp.open("GET", "http://localhost:1979/PolarSpeakers/servlet/mailCheck.do?e=" + param1, true) xmlHttp.onreadystatechange = handleStateChange; xmlHttp.send(null); } } function handleStateChange() { if(xmlHttp.readyState==4) { if(xmlHttp.status==200) { var message = xmlHttp.responseXML .getElementsByTagName("valid")[0] .childNodes[0].nodeValue; if (message == "Unregistered") { validEmail = true; document.getElementById("result").style.color = "green"; } else { validEmail = false; document.getElementById("result").style.color = "red"; } document.getElementById("result").innerHTML = message; } else { alert("Error checking e-mail address - " + xmlHttp.status + " : " + xmlHttp.statusText); } } } function createCaptchaRequest() { if(window.ActiveXObject) { xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp2=new XMLHttpRequest(); } } function startCaptchaRequest() { alert('made it to captcha requeswt'); createCaptchaRequest(); var param1 = Recaptcha.get_challenge(); var param2 = Recaptcha.get_response(); xmlHttp2.open("POST", "http://localhost:1979/PolarSpeakers/servlet/captchaCheck.do?c=" + param1 + "&r=" + param2, true) xmlHttp2.onreadystatechange = handleStateChangeCaptcha; xmlHttp2.send(null); } function handleStateChangeCaptcha() { if(xmlHttp2.readyState==4) { if(xmlHttp2.status==200) { var message = xmlHttp2.responseXML .getElementsByTagName("result")[0] .childNodes[0].nodeValue; if (message == "Valid") { alert("captcha valid"); validCaptcha = true; } else { document.getElementById("error").innerHTML = message; validCaptcha = false; } } else { alert("Error checking captcha validity - " + xmlHttp2.status + " : " + xmlHttp2.statusText); } } } Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> |