JavaScript - Contact Form Validation Server And Client
I have heard that it is wrong to just do client validtion. SO can anyone help me with my form?
The code below, has client validation and php and I am not sure that I have got it right. Also I would need to cover server side validation too but have no idea on how to do this. I must say I have very small knowledge of JS. Does anyone know the easiest method of doing forms with php, JS server and client side validation. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta content="en" name="language" /> <meta content="Seniors community venue contact details, Seniors community venue contact form, email, address, and telephone number" name="description" /> <meta content="Seniors community venue contact form, email, telephone, address" name="keywords" /> <title>Seniors Community Venue - Contact details</title> <link href="../styles/mainstyle.css" rel="stylesheet" type="text/css" /> <link href="../styles/navigation.css" rel="stylesheet" type="text/css" /> <link href="../styles/layout.css" rel="stylesheet" type="text/css" /> <link href="http://fonts.googleapis.com/css?family=Cabin|Ubuntu" rel="stylesheet" type="text/css" /> <link href="../styles/form.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../javascript/validate.js"></script> <style type="text/css"> .antispam { display: none; } </style> <script type="text/javascript"> var first = "enquiries"; var last = "seniors260.org";</script> </head> <body> <div id="bodyblock"> <div id="container"> <div id="header"> <div class="indentmenu"> <ul> <li><a href="faqs.html">FAQS</a></li> <li><a href="venue_location.html">Location</a></li> <li><a href="about_us.html">About Us</a></li> <li class="first"><a href="home.html">Home</a></li> </ul> </div> <div class="logo_venue"> <img alt="Seniors Community Venue logo" height="100" src="../images/venue_logo.gif" width="200" title="Return to hompage" /></div> <div class="top2"> <p class="tagtitle">"The best community venue<br /> your money can buy"</p> <address class="top"> 260 Stanstead Road<br /> London SE23 1DD<br /> 020 8699 4977</address> </div></div> <div class="indentmenu2"> <ul> <li><a href="room_hire.html">Room Hire</a></li> <li><a href="testimonials.html">Testimonials</a></li> <li><a href="album.html">Photo Album</a></li> <li class="first2"><a href="venue_donations.html">Donations</a></li> </ul> </div> <div id="content"> <h1>Venue Contact Details</h1> <h2>Contact Form</h2> <div id="form_box"> <form id="form" action="../php_files/submit2.php" onsubmit="return validate()" enctype="multipart/form-data" method="post" name="form_to_email" /> <fieldset> <legend>Contact Form</legend> <p><label for="name"><span>Name</span></label><input id="name" name="name" size="35" type="text" /></p> <p><label for="email"><span>Email</span></label><input id="email" name="email" size="35" type="text" /></p> <p><label for="subject"><span>Subject</span></label><input id="subject" name="subject" size="35" type="text" /></p> <p class="antispam">Leave this empty: <br /> <input name="url" /></p> </fieldset><fieldset> <legend>Message</legend> <textarea id="message" cols="50" name="message" rows="10"></textarea></fieldset><fieldset> All fields Required </fieldset><p> <input id="submit" name="submit" type="submit" value="Submit" /></p> Similar TutorialsI know that Javascript is client side, but I'd like to know the best way to populate HTML drop downs in real time based on information typed in the other HTML form fields with information found on the server as opposed to the client. For instance if a user wants to select certain files located in a directory on the server, as they type in the pathname supposedly containing the files the drop downs continually refresh themselves with the server files listed in that directory (if it exists, and apache has permissions to see what's inside) as if it was showing client files instead. What would be nice is if my browser could continually query the server for some of its private information and not have to refresh itself to obtain it, whether that means the server-side would have to continually refresh itself makes no difference to me as long as the client-side doesn't have to. But I guess this is not possible because no matter what you would have to at least refresh the client-side page once? Submitting the form to a CGI or PHP script would not work because I need this functionality to help populate the form BEFORE I send it. I would like to not have to press a button to update the form every time I change the pathname and need to update the drop downs since this would be annoying. I'm open to anything that could do this or something similar not just Javascript. I'm not sure if you could accomplish this by converting the HTML page to CGI/PHP and having it continually reload itself without refreshing the page? I'm not worried about any security risks this may pose because: 1) The server is located on company intranet which is firewalled 2) I could always password protect and encrypt all transmissions, making sure only authorized users use the app 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, The following code is not working whose purpose is to validate the form with javascript. Please Help . Code: <html> <head> <script type='text/javascript'> function formValidator() { // Make quick references to our fields var firstname = document.getElementById('firstname'); var addr = document.getElementById('addr'); var zip = document.getElementById('zip'); var state = document.getElementById('state'); var username = document.getElementById('username'); var password = document.getElementById('passwd'); var email = document.getElementById('email'); var cpassword=document.getElementById('pass2'); var txtar=document.getElementById('ta'); var rad=document.getElementById('r1'); var cbox =document.getElementById('r1'); // Check each input in the order that it appears in the form! if(isAlphabet(firstname, "Please enter only letters for your name")) { if(isAlphanumeric(addr, "Numbers and Letters Only for Address")) { if(isNumeric(zip, "Please enter a valid zip code")) { if(madeSelection(state, "Please Choose a State")) { if(lengthRestriction(username, 6, 8)) { if(plengthRestriction(password,4,6)) { if(confpass(cpassword,"Please confirm")) { if(emailValidator(email, "Please enter a valid email address")) { if(istextareablank(txtar,"Please enter some text")) { if(isradiobuttselected(rad,"Please select any one radio buttons")) { if(ischeckboxselected(cbox,"Please select at least one checkbox")) { return true; } } } } } } } } } } } return false; } function notEmpty(elem, helperMsg){ if(elem.value.length === 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function lengthRestriction(elem, min, max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter username between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } function plengthRestriction(elem, min,max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter password between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function confpass(elem,helperMsg) { if ( confPasswd === "" ) { alert("Please fill in the Confirm Password"); document.forms[0].elements[7].focus( ); return false; } else if (document.forms[0].elements[6].value != document.forms[0].elements[7].value) { alert( "Your passwords do not match. Please retype and try again."); return false; } } function isEmpty(s) { return ((s === null) || (s.length === 0)); } function istextareablank(elem,helperMsg){ var i; <!-- Is empty? --> if (isEmpty(s)) return true; <!-- Search through string's' characters one by one until we find a non-whitespace character. --> for (i=0; i < s.length; i++) { <!-- Check that current character isn't' whitespace.--> var currchar = s.charAt(i); if (whitespace.indexOf(currchar) == -1) return false; } <!-- All characters are whitespace. --> return true; } function isradiobuttselected(elem,helperMsg){ <!-- Check to see if atleast one is checkbox checked or not--> for (j=10; j<=11; j++) { if(document.forms[0].elements[j].checked) { break; } else if (j>=11) { alert("Atleast Check on one of the radio buttons"); document.forms[0].elements[j].focus(); return (false); } } return(true); } function ischeckboxselected(elem,helperMsg) { for (j=12; j<=13; j++) { if(document.forms[0].elements[j].checked) { break; } else if (j>=13) { alert("Atleast Check on One of Our Services"); document.forms[0].elements[j].focus(); return (false); } } return(true); } </script> </head> <body> <form onsubmit='return formValidator()' > <br /> First Name: <input type='text' id='firstname' /><br /><br /> Address: <input type='text' id='addr' /><br /><br /> Zip Code: <input type='text' id='zip' /><br /><br /> State: <select id='state'> <option>Please Choose</option> <option>AL</option> <option>KE</option> <option>TX</option> <option>CH</option> </select><br /> Username(6-8 characters): <input type='text' id='username' /><br /><br /> Password(min 4 chars):<input type="password" id='passwd' /> <br/><br /> Confirm Password: <input id="pass2" Type="password" /><br/><br /> Email: <input type='text' id='email' /><br /><br /> Something about Yourself : <textarea name="1" cols="17" rows="4" id="ta"></textarea><br/><br /> Free Membership <input type="radio" id="r1"/> Paid Membership <input type="radio" id="r1"/><br/><br/> Friendship<input type="checkbox" id="box1" /> Networking <input type="checkbox" id="box1" /><br /><br /> <input type='submit' value='Submit' /> </form> </body> </html> i cant see to get my finger on the validation correctly, im trying to achieve that: (*) Required fields are required in the final submission All other fields are validated by their content type But all fields without (*) Required are not needed for the form to be submitted http://www.on-media.co.uk/clients/hlmd/ http://www.on-media.co.uk/clients/hl...ipt/contact.js is the below code: Code: function formValidator(){ // Make quick references to our fields var name = document.getElementById('name'); var sname = document.getElementById('sname'); var phone = document.getElementById('phone'); var cell = document.getElementById('cell'); var calltime = document.getElementById('calltime'); var email = document.getElementById('email'); var address = document.getElementById('address'); var zip = document.getElementById('zip'); var loana = document.getElementById('loana'); var loanb = document.getElementById('loanb'); var balance = document.getElementById('balance'); // Check each input in the order that it appears in the form! if(isAlphabet(name, "Please enter only letters for your name")){ if(isAlphabet(sname, "Please enter only letters for your surname")){ if(isNumeric(phone, "please enter only numbers for your phone number")){ if(isNumeric(cell, "please enter only numbers for your cell number")){ if(madeSelection(calltime, "Please select a time for your callback")){ if(isAlphanumeric(address, "please enter your address in numbers and letters")){ if(isNumeric(zip, "Please enter a valid zip code")){ if(emailValidator(email, "Please enter a valid email address")){ if(isAlphanumeric(loana, "Please enter the value of your loan")){ if(isAlphanumeric(loanb, "Please enter the value of your loan")){ if(madeSelection(balance, "Select the duration you are behind on your loan re-payments")){ return true; } } } } } } } } } } } return false; } function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } is my form: Code: <form onsubmit='return formValidator()' ><div id="contactfC"> <div id="contactf1"> <table width="240" border="0"> <tr> <td width="102"><span style="color:#F00;">*</span>Name:</td> <td width="108"><input name="name" type="text" id="name" size="15" /></td> </tr> <tr> <td><span style="color:#F00;">*</span>Surname:</td> <td><input name="sname" type="text" id="sname" size="15" /></td> </tr> <tr> <td><span style="color:#F00;">*</span>Phone Number:</td> <td><input name="phone" type="text" id="phone" size="15" /></td> </tr> <tr> <td>Cell Number:</td> <td><input name="cell" type="text" id="cell" size="15" /></td> </tr> <tr> <td>Best time to call:</td> <td><select name="calltime" id="calltime"> <option value="Morning">Morning</option> <option value="Afternoon">Afternoon</option> <option value="Evening">Evening</option> <option value="Anytime">Anytime</option> <option value="Please Choose" selected="selected">Please Choose</option> </select></td> </tr> <tr> <td>Address:</td> <td><textarea name="address" id="address" cols="15" rows="3"></textarea></td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </div> <div id="contactf2"> <table width="245" border="0"> <tr> <td width="133"><span style="color:#F00;">*</span>Zip Code:</td> <td width="118"><input name="zip" type="text" id="zip" size="15" /></td> </tr> <tr> <td><span style="color:#F00;">*</span>Email:</td> <td><input name="email" type="text" id="email" size="15" /></td> </tr> <tr> <td><span style="color:#F00;">*</span>1st Loan Amount:</td> <td><input name="loana" type="text" id="loana" size="15" /></td> </tr> <tr> <td>2nd Loan Amount:</td> <td><input name="loanb" type="text" id="loanb" size="15" /></td> </tr> <tr> <td><span style="color:#F00;">*</span>Balance Past Due:</td> <td><select name="balance" id="balance"> <option value="One Month">1 Month</option> <option value="Two Months">2 Months</option> <option value="Three Months">3 Months</option> <option value="Four Months">4 Months</option> <option value="Five Months +">5 Months +</option> <option value="Not Applicable">N/A</option> <option value="Please Choose" selected="selected">Please Choose</option> </select></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td><input type="submit" name="button" id="button" value="Submit" /></td> </tr> </table> </div> </div></form> i appricate any help thanks Hi Everybody. i have a contact form here PHP Code: <form id="form1" method="post" action="/contact.php" onsubmit="return validate(this)"> <p> <label for="name">Name:</label> <input type="text" name="name" id="name" /> <img src="alert.gif" alt="" class="alertImg" /> </p> <p> <label for="number">Mobile:</label> <input type="text" name="number" id="number" /> <img src="alert.gif" alt="" class="alertImg" /> </p> <p> <label for="email">Email:</label> <input type="text" name="email" id="email" /> <img src="alert.gif" alt="" class="alertImg" /> </p> <p> <label for="msg">Comments:</label> <textarea name="msg" id="msg" cols="30" rows="3"></textarea> <img src="alert.gif" alt=""class="alertImg" /> </p> <p> <input class="submit_btn" type="image" src="images/submit_btn.gif" name="submit" value="Submit" /></p> <!-- --> </form> and i have an external js script to validate the form and the code is below PHP Code: var alertImgs = []; var nImage = ""; function validate(nForm){ for (i=0; i<alertImgs.length; i++) { nImage[alertImgs[i]].style.visibility = "hidden"; } var nName = nForm['name']; var nMobile = nForm['number']; var nEmail = nForm['email']; if (nFirstName.value.replace(/s/g, "").length < 1) { alert('Please Enter Your Name'); document.images[alertImgs[0]].style.visibility = "visible"; return false; } if (!/[ds-]+$/.test(nmobile.value) || !/d{10}/.test(nmobile.value.replace(/[s-]/g, ""))) // must contain 10 digits; { alert('Enter your mobile phone number'); document.images[alertImgs[2]].style.visibility = "visible"; return false; } if (!/^w+[w|.|-]{0,1}w*[w|.|-]{0,1}w*@w+[w|-]{0,1}w*[w|-]{0,1}w*.{1,1}[a-z]{2,4}$/.test(nEmail.value)) { alert('Invalid Email'); document.images[alertImgs[3]].style.visibility = "visible"; return false; } if (nForm['msg'].value == "") { alert('Please write a comment'); document.images[alertImgs[4]].style.visibility = "visible"; return false; } alert('Thank you for your submission'); return true; } function init(){ nImage = document.images; var imgFileName = ""; for (i=0; i<nImage.length; i++) { imgFileName = nImage[i].src; imgFileName = imgFileName.substring(imgFileName.lastIndexOf("/")+1,imgFileName.length) if (imgFileName == "alert.gif") { alertImgs[alertImgs.length] = i; nImage[i].style.visibility = "hidden"; } } } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); Could anyone tell me why it wont work for me and is there any problem with the code? Thanks for your help if you give some Hello, I have an existing php contact form which incorporates php validation (required name with only characters, valid email address format, and minimum message length) and re-captcha. I would like to add some "real time" validation to the fields on my form (there are 3 fields - name, email and message) before the "Submit" button is pressed. For example when the user tabs from one text box to the next but hasn't filled in the required information. I am totally new to any type of java, but am I right in thinking I need either JavaScript, Ajax or JQuery to perform real-time validation? If so, which should I be looking into and are there any basic examples of form validation? I want to keep my pup validation as I'm aware that php is client-side but still needed as people can turn Java off in their web browsers. Any tips and pointers will be very much appreciated! Thankyou, Tom Hi, I am trying to follow this tutorial and make a login feature for my apphttp://code.google.com/webtoolkit/do...unication.html to use GWT's remote procedure calls (RPC) to have server client communication to eventually make a web app that talks to a database. I thought I followed it exactly but when the async returns it fails and returns an exception: "com.google.gwt.user.client.rpc.InvocationException" Can someone please take a look at the client code, it must be something stupid that I am doing wrong. Thanks Here's the code: In the calling client class: Code: private MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class); ((ServiceDefTarget)svc).setServiceEntryPoint(GWT.getModuleBaseURL()); //loginButtonListener btnDBLogin.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { svc.checkLogin(txtUsername.getText(),txtPassword.getText(), new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { if (result.booleanValue() == true) { System.out.println("Works"); } else { System.out.println("Invalid UserName or Password"); } } public void onFailure(Throwable ex) { System.out.println("FAILU " + ex.toString()); } });//end checkLogin }//end onCLICK });//endbtnlistener MyService.java (client interface) Code: package com.rob.projects.client; import com.google.gwt.user.client.rpc.RemoteService; public interface MyService extends RemoteService { public Boolean checkLogin(String userName, String password); } MyServiceImpl.java (server code) Code: package com.rob.projects.server; import com.rob.projects.client.MyService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class MyServiceImpl extends RemoteServiceServlet implements MyService { private static final long serialVersionUID = 1L; public Boolean checkLogin(String userName, String password) { System.out.println(userName); if (userName.equalsIgnoreCase("bingo")) { // Check the database return true; } else return false; } } web.xml (to specify where the servlet is) PHP Code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- <servlet> path='MyService'class='com.rob.projects.server.MyServiceImpl' </servlet> --> <!-- Servlets --> <servlet> <servlet-name>MyServiceImpl</servlet-name> <servlet-class>com.rob.projects.server.MyServiceImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServiceImpl</servlet-name> <url-pattern>/satapp</url-pattern> </servlet-mapping> <!-- Default page to serve --> <welcome-file-list> <welcome-file>SATapp.html</welcome-file> </welcome-file-list> </web-app> Ok, so I consider myself to be fairly proficient with programming in general, although I am admittedly new to bi-directional networking. So here I am asking about methodological approaches. A non-disclosure clause prevents me from giving any details, but I don't think they would actually be pertinent. What is important is that the system must accept input from client side Javascript from many users and disseminate that input (once processed) to a number of users. In a way, think multi-channel chat system (totally different environment, but the mechanisms seem similar). As I see it, I have two options: periodic server polling, or server-sent events (compatibility with IE is not a requisite). So, my question is, which method (of these two or even something that I am not thinking of) is superior from the standpoint of server bandwidth? Periodic server polling obviously seems as if it would send a great many unneeded requests, but my hesitation for dismissing this method is that I don't see any client being idle for any considerable length of time (thus the client will send commands to the server quite often) and it simplifies my server software by delegating that section of logic (which data chunks need to be updated) to client CPU's. Additionally, I can throttle the update period based on server load. Server-sent events initially sounded like a great idea until I thought about the extreme likelihood of a large number of users (upwards of a hundred) interaction with the same chunk of data, thus requiring that each client receive an update every time another client does anything, which is likely once ever second or two, thus resulting in hundreds of updates being sent to hundreds of clients every second. Sounds similar to a denial of service situation to me. Anyway, I think I already know what I'm going to do for this project, but thought that this might be a good way to introduce myself to these forums. Hello, I have two problems. Firstly I am trying to make a form with client side validation but I have come across a problem. I need to validate the whole form under just one button but for validating email and phone number I have two different buttons and I am not sure how to make all the code run under just one button when it is submitted. The second problem is with validating the phone number. I am sure the code and javascript is fine, but for some reason it will not work. Here is my code: HTML Code: <!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"/> <script type="text/javascript" src="client_validation.js" /> </script> <link rel="stylesheet" type="text/css" href="Client validation.css" /> <title> Client Validation </title> </head> <body> <form name="contact_form" method="post" action="submit" onsubmit="return validate_form ( );"> <h3><strong>Client Validation</strong></h3> <p>Your Name: <input type="text" name="text1"></p> <p>Your Last Name: <input type="text" name="text2"></p> <p>Email: <input type="text" id="email" name="text3"></p> <p>Phone: <input type="text" name="text4"></p> <p>Address: <textarea cols="20" rows="5" name="text5"></textarea></p> <p>Do you agree to the Terms and Conditions? <input type="checkbox" name="text6" value="Yes"> Yes <p><input type="submit" name="send" value="Send Details"></p> </form> Your Email: <form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');"> <input type="text" id="email" name="email" /> <input type="submit" value="Submit" /> <form method="post" action="data.php" name="form1"> <p>Enter Number <input type="text" name="phoneNo"></p> <input type="button" name="btn1" value="submit" onClick="CheckNumber()"> </body> </html> JAVASCRIPT Code: function validate_form ( ) { valid = true; if ( document.contact_form.text1.value == "" ) { alert ( "Please fill in the 'Your First Name' box." ); valid = false; } if ( document.contact_form.text2.value == "" ) { alert ( "Please fill in the 'Your Last Name' box." ); valid = false; } if ( document.contact_form.text5.value == "" ) { alert ( "Please fill in your address." ); valid = false; } if ( document.contact_form.text6.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; } return valid; } function validate(form_id,email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.forms[form_id].elements[email].value; if(reg.test(address) == false) { alert('Invalid Email Address'); return false; } } function CheckNumber() { var PhoneNumber=document.form1.phoneNo.value; for (var i=0; i<PhoneNumber.length; i++) { var c=PhoneNumber.charAt(i); if (!(c>0 || c<9)){ alert("This is not a valid Phone Number"); break; } } } I hope you guys can help. Thank you Hello, and thank you for taking the time to read over my thread. I'm pretty new with Javascript coding and have been working with an example script for a new membership registration form. The original form seemed to have worked for most intents and purposes but it only contained one entry for a password field. Naturally I felt it needed a conformation field and have tried to stick one in, which is where I ran into problems. I successfully made the script throw an alert box if the two forms are the same, but it then throws another alert box of undefined function as well as throwing the same undefined function alert box even if the fields are a match. Hopefully a knowledgeable person could take a quick look at this and kindly inform me of where I'm going wrong? The code contains two of my numerous attempts to make it work (one commented out, it was easier to remember different things I have tried before to leave then in but commented out, I'm sure you all are quite familiar with that idea). Anyhow, here's the code, thank you in advance. Code: <!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>Register</title> <link href="css/master.css" rel="stylesheet" type="text/css" /> <style> .signup {border:1px solid #999999}</style> <script> function validate(form) { fail = validateFirstname(form.firstname.value) fail += validateSurname(form.surname.value) fail += validateUsername(form.username.value) fail += validatePassword(form.password.value) fail += validateConfirmpass(form.confirmpass.value) fail += validateAge(form.age.value) fail += validateEmail(form.email.value) if (fail == "") return true else { alert(fail); return false } } </script> <script> function validateFirstname(field) { if (field == "") return "No First name entered. \n" return "" } function validateSurname(field) { if (field == "") return "No Surname entered. \n" return "" } function validateUsername(field) { if (field == "") return "No Username was entered. \n" else if (field.length < 5) return "Usernames must be at least 5 characters. \n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ are valid in Usernames. \n" } function validatePassword(field) { if (field == "") return "No Password was entered. \n" else if (field.length < 6) return "Passwords must be at least 6 characters. \n" else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) || !/[0-9]/.test(field)) return "For your account security Passwords require atleast one uppercase, one lowercase, and one number to be valid. \n" } function validateConfirmpass() { var p1 = document.getElementById('password').value; var p2 = document.getElementById('confirmpass').value; if (p1 !== p2) alert("The password fields do not match."); } //function validateConfirmpass(field) { // var password = document.getElementById('password').value; // var confirmpass = document.getElementById('confirmpass').value; // if (password !== confirmpass) { // return "The password and confirmation do not match. \n" // } //} function validateAge(field) { if (isNaN(field)) return "No Age was entered.\n" else if (field < 18 || field >110) return "Age is required to be between 18 and 110 years. \n" return "" } function validateEmail(field) { if (field == "") return "No Email was entered. \n" else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address entered is invalid. \n" return "" } </script> </head> <body> <table class="signup" border="0" cellpadding="2" cellspacing="5"> <th colspan="2" align="center">Registration Form</th> <form method="post" action="tnssignup.php" onsubmit="return validate(this)"> <tr><td>First name</td><td><input type="text" maxlength="32" name="firstname" /></td> </tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td> </tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td> </tr><tr><td>Password</td><td><input type="text" maxlength="12" id="password" name="password" /></td> </tr><tr><td>Confirm Password</td><td><input type="text" maxlength="12" id="confirmpass" name="confirmpass" /></td> </tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td> </tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td> </tr><tr><td colspan="2" align="center"> <input type="submit" value="Register" /></td> </tr></form></table> </body> </html> Hi people, I need help as follows: On the server side I have a php generated session parameter. I need to pass it to javascript on the client side page. I saw on the web the following solution: <script language="JavaScript"> var mySessionVar="<%= Session["MySessionVar"] %>"; </script> I tried it but it did not work. I could not find any explanation of this syntax - will appreciate one. Any suggestions, maybe in another way? Thanks I have a form field that needs to be validated in a hidden Iframe which is driven by Coldfusion. Which is working fine. But the same form field also need do some client side validation as well if Server side (iframe) validation passes. I thought I could create a javascript function, in it call a server side validate and then client side, but without any success. It does not process in the order as expected. Javascript always go first, then the server side validation. I tried to delay the client side with time delay, then server side did process first, but client function could not recognize the parameter passed. here is the function: Function doValidation(param1,param2,param3,param4) { .... document.iframName.src='serverValidate.cfm?m1=param1&p2=param2'; .... clientValidate(param3,param4); } If only I could have serverside validation return a value the function, then I could defined that value then the the clientValidate(param3,param5) to start other wise warn with a message. Both validation does work seperately. The issue is it triggered by one onChange event I have to put them in one function. Maybe I am on a wrong track. Please advise if anyone could have better solution. Thanks in advance. JT I have an auto submit form example.. Code: <form name = "backtosource" method="POST" and the rest of this is fine> blah blah </form> <script type="text/javascript"> function process_data_return() { document.backtosource.submit(); } </script> <script type="text/javascript"> <!-- process_data_return(); // --> </script> so this works for everyone of my people other than one who is on a debian server, we all use centos. i know this is cleint side but i wanted to mention that. this user has the js enabled on all his browsers. so what would cause his browser not to execute the js auto submit, we know this to be the issue but cannot resolve. thanks i guess i could try the old cdata wrap trick Code: // <![CDATA[ js code // ]]> but i dont want it to affect those that this is working. What is a good switch value to use so i can build an if statement. Is there a current local value i can trap for comparison Not totally sure this is in the correct section but here goes!... I've coded up my form in html / css and added some scripts i found online that should prevent users from submitting the form without the fields filled in. However the form only seems to work in chrome, safari and yet firefox it lets users submit without needing anything filled in. my form is he http://www.rhombusone.com/projecttiger/contact.html Also targeting the error text so that it appears below the field box instead of being all over the place, what value am i targeting? Thanks M 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, I have created a website which employs javascript contact forms. There is a javascript contact form located on the left of every page of the website which works fine but on the contact page where there are two forms the main form on the page does not work. The contact us page is located he http://www.goodletterwriting.co.uk/contact-us.html The two javascript files that are being used a http://www.goodletterwriting.co.uk/scripts/scripts.js & http://www.goodletterwriting.co.uk/scripts2/scripts2.js Can somebody please help? Thanks in advance, Peter Basically I can't get it to work. I'm following this tutorial and I'm not able to hide the error messages, or just get the form to submit. I could really use some direction. Here is the page I am working on: http://www.mustlovepink.com/public_html/contact.php Code: // Form submission $('#contact-form').submit(function() { // Hide any message $('span#contact-msg').css('opacity', 0); // Build data string var fields = [ 'name', 'email', 'message' ]; var data = 'ajax=1'; for (var i = 0; i < fields.length; i++) data += '&' + fields[i] + '=' + encodeURI($('#' + fields[i]).val()); // Submit $.ajax( { url : $('#contact-msg').attr('action'), dataType: 'json', data: data, type: 'POST', success: function(data) { if (data.sent == true) { $('span#contact-msg').html('Thanks for the message. I will get back to you as soon as possible.'); $('#send').css('backgroundPosition', '-207px -168px'); $('#send').attr('disabled', 'disabled'); } else $('span#contact-msg').html(data.error); $('span#contact-msg').animate( { opacity: 1 }, 400); } }); return false; }); I got this code for an contact form, but where can I set the email address to send to? Does someone know how to let 2 of the same type of contact form, working on the same page? Because i have the contact form on the footer of my page, and when you visit at the mennu: contact us, the same contact form will be shown. But it wont work, only the one in the footer. Hello JScript gurus, though I am quite an advanced and experienced VB& .NET programmer, I am totally new to Jscript coding, (I don't actually code Jscript) but I build websites all the same too. I am also new here. I really need help from you gurus here. I am working on a website and I really wish to incorporate a contact or an order form to it so that when the user fills in the fields and clicks send, I receive the data in my email. I have made some searches and found quite a few but all didn't touch on how I retrieve my data. Please help me. I will be very grateful. Thank you. |