JavaScript - (basic) Web Form Validation And Javascript
Hello, I am a computing pupil currently taking part in a computer science project at GCSE level. Our project is a research task regarding web form validation, JavaScript and embedding JavaScript into HTML code. I have no prior knowledge of any of these topics, so would be very interested in hearing your opinions on the aboce. I would also like to know your opinion on how effective JavaScript validation is, possibly in your field of work, or just your experience of using it?
Thanks in advance, Ellen Similar TutorialsI'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> Hi i need help with an assignment that validates forms using javascript. Using my instructors example as a guide, i wrote this if you click submit on the example it properly returns false and displays an error message, in my assignment it does nothing but submit to the echo while im trying to get an error message. The assignment is unfinished but i wanted to test out the first bit of code and its not working. could anyone tell me how to do this? i don't know anything about javascript, but it is the most elegant way to validate a form. i have 2 questions asked in a form (name=questions). First question are radio buttons with 3 answers (name=answer). Second is a questions with a numeric value as answer with max 10 characters (name=questionb). Could anyone tell me where to start? Thanks, Walter I have a form validation script that runs perfect. Now i want to add one more field to the form and want to make some fields "required" but i dont know how to do this. Please help me. I am also attaching the relevant files. Thanks in advance. Fields to add: 1. Social Security Number (Same as Home Telephone but allows 3 digits in 1st field, 2 in 2nd and 4in 3rd field (123)-(12)-(1234)) Fields to make "required" : Social Security Number First Name Last Name The Script Code: var phoneRegEx = /^(?:(?:\(?(?:(?:[246-8](?:(?:[02-8][0-9])|(?:1[02-9])))|(?:3(?:(?:[02-68][0-9])|(?:1[02-9])))|(?:5(?:(?:[02-46-8][0-9])|(?:5[0-46-9])|(?:1[02-9])))|(?:9(?:(?:[02-578][0-9])|(?:1[02-9]))))\)?)(?:[\- ]?)(?:(?:700(?:[\- ]?)(?:(?:[0-35-9][0-9]{3})|(?:4[02-9][0-9]{2})|(?:41[0-35-9][0-9])|(?:414[02-9])))|(?:(?:(?:[23468][02-9][0-9])|(?:[2-9]1[02-9])|(?:5(?:(?:5[0-46-9])|(?:[02346-9][0-9])|(?:1[02-9])))|(?:7(?:(?:[2-9][0-9])|(?:0[1-9])|(?:1[02-9])))|(?:9(?:(?:[0234689][0-9])|(?:1[02-9])|(?:5[1-7])|(?:7[0-5789]))))(?:[\- ]?)(?:[0-9]{4}))))$/; var error // used to store RowNames for errored elements. var isOptRequired = false; function ValidateQuoteRequest(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); CheckDropDown('Month', 'row_date', frm); CheckDropDown('Day', 'row_date', frm); CheckDropDown('Year', 'row_date', frm); CheckDate('Month', 'Day','Year', 'row_date', frm, 'True'); CheckDropDown('Sex', 'row_sex', frm); CheckDropDown('Height_Feet', 'row_Height', frm); CheckDropDown('Height_Inches', 'row_Height', frm); CheckIntegerField('Weight', 'row_Height', frm, 'True'); CheckDropDown('Tobacco', 'row_tobacco', frm); CheckFrequency('Frequency', 'row_tobaccotype', frm, 'True'); CheckPhone('workphone,homephone', 'row_workphone,row_homephone', frm, 'False'); CheckEmail('email', 'row_email', frm, 'False'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRequestApplication(frm) { if(isBrowserCompatible()) { error = new Array(); CheckTextField('firstname', 'row_firstname', frm,); CheckTextField('lastname', 'row_lastname', frm); CheckTextField('address', 'row_address', frm); CheckTextField('city', 'row_city', frm); CheckTextField('state', 'row_state', frm); CheckZip('zip', 'row_state', frm, 'True'); CheckPhone('work_phone_number_,home_phone_number_,cell_phone_number_', 'row_work_phone_number_,row_home_phone_number_,row_cell_phone_number_', frm, 'True'); CheckNumericField('work_phone_number_4', 'row_work_phone_number_', frm, 'False'); CheckEmail('email', 'row_email', frm, 'True'); CheckDropDown('premium_quoted', 'row_premium_quoted', frm); CheckRadioButton('Residency', 'row_Residency', frm); CheckRadioButton('spouse_policy', 'row_spouse_policy', frm); CheckSpouseTextField('spouse_first_name', 'row_spouse_first_name', frm); CheckSpouseTextField('spouse_last_name', 'row_spouse_last_name', frm); CheckDropDown('AgentID', 'row_AgentID', frm); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRBCRequestApplication(frm) { if(isBrowserCompatible()) { error = new Array(); CheckTextField('firstname', 'row_firstname', frm); CheckTextField('lastname', 'row_lastname', frm); CheckTextField('address', 'row_address', frm); CheckTextField('city', 'row_city', frm); CheckTextField('state', 'row_state', frm); CheckZip('zip', 'row_state', frm, 'True'); CheckPhone('work_phone_number_', 'row_work_phone_number_', frm, 'True'); CheckEmail('email', 'row_email', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRBCQuoteRequest(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); CheckDropDown('Sex', 'row_Sex', frm); CheckDate('Month', 'Day','Year', 'row_date', frm, 'True'); CheckDropDown('Amount', 'row_Amount', frm); CheckRadioButton('coverageTerm', 'row_coverageTerm', frm); CheckRadioButton('tobacco', 'row_tobacco', frm); CheckTextField('firstname', 'row_firstname', frm); CheckTextField('lastname', 'row_lastname', frm); CheckPhone('home_phone_number_', 'row_home_phone_number_', frm, 'True'); CheckEmail('email', 'row_email', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateHealth(frm) { if(isBrowserCompatible()) { error = new Array(); CheckEmail('Email', 'row_Email', frm, 'True'); CheckZip('ZipCode', 'row_ZipCode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateHome(frm) { if(isBrowserCompatible()) { error = new Array(); CheckEmail('Email', 'row_Email', frm, 'True'); CheckZip('ZipCode', 'row_ZipCode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateLTC(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateAuto(frm) { if(isBrowserCompatible()) { error = new Array(); CheckZip('zipcode', 'row_zipcode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } //------- function CheckAnnualIncome (ElmtName, RowName, frm,isReq) { if(!frm.elements[ElmtName + '_decline'].checked) CheckNumericField (ElmtName,RowName, frm, isReq); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckTextField (ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; if(trim(frm.elements[ElmtName].value) == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //---- function CheckSpouseTextField (ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; for(var i=0;i < frm.spouse_policy.length; i++) { if(frm.spouse_policy[i].checked && frm.spouse_policy[i].value == 'yes') { CheckTextField (ElmtName, RowName, frm); }else{ removeErrorFormatting(ElmtName, RowName, frm); } } } //------ function CheckNumericField(ElmtName, RowName, frm, isReq) { if (frm.elements[ElmtName].value != '' || isReq.toLowerCase() == 'true') { var val = frm.elements[ElmtName].value.replace(/,/g,''); val = val.replace('$', ''); if(parseFloat(val)!=(val*1) || val == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } else { removeErrorFormatting(ElmtName, RowName, frm); } } function CheckIntegerField(ElmtName, RowName, frm, isReq) { if (frm.elements[ElmtName].value != '' || isReq.toLowerCase() == 'true') { if(frm.elements[ElmtName].value.indexOf('.') != -1 || (frm.elements[ElmtName].value % 1) != 0 || frm.elements[ElmtName].value == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } else { removeErrorFormatting(ElmtName, RowName, frm); } } //----- function CheckEmail (ElmtName, RowName, frm, isReq) { //add for optimost required field testing. if(isOptRequired) isReq = 'true'; var regEx; regEx = /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/; if(!regEx.test(frm.elements[ElmtName].value) && (frm.elements[ElmtName].value != '' || isReq != 'False')) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckDate(ElmtMonth, ElmtDay, ElmtYear, RowName, frm, isReq) { var Day = frm.elements[ElmtDay].options[frm.elements[ElmtDay].selectedIndex].value; var Month = frm.elements[ElmtMonth].options[frm.elements[ElmtMonth].selectedIndex].value - 1; var Year = frm.elements[ElmtYear].options[frm.elements[ElmtYear].selectedIndex].value; var DateObj = new Date(Year,Month,Day); if ( DateObj.getMonth() != Month) { ThrowError(RowName, RowName, frm); } else { removeErrorFormatting(RowName, RowName, frm); } } //------- function CheckZip(ElmtName, RowName, frm, isReq) { var regEx regEx = /^\d{5}$|^\d{5}-\d{4}$/; if(!regEx.test(frm.elements[ElmtName].value) && (frm.elements[ElmtName].value != '' || isReq != 'False')) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------ function CheckDropDown(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; if(frm.elements[ElmtName].options.selectedIndex == 0) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckRadioButton(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; var radioChecked = false; for(var i=0;i < frm.elements[ElmtName].length; i++) { if(frm.elements[ElmtName][i].checked) { radioChecked = true; break; } } if(!radioChecked) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckCheckboxes(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; var checkboxChecked = false; for(var i=0;i < frm.elements[ElmtName].length; i++) { if(frm.elements[ElmtName][i].checked) { checkboxChecked = true; break; } } if(!checkboxChecked) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckPhone(ElmtNames, RowNames, frm, isReq) { //add for optimost required field testing. if(isOptRequired) isReq = 'true'; checkPhoneNumbers(ElmtNames, RowNames, frm, isReq) } //------ function CheckFrequency(ElmtName, RowName, frm) { var Tobacco = new Array(3,4,5,6,7,8); var ThrowErrorFlag = false; for(i = 0; i < Tobacco.length; i++) { if(Tobacco[i] == frm.elements["Tobacco"].options[frm.elements["Tobacco"].selectedIndex].value && frm.elements["Frequency"].options.selectedIndex == 0) { ThrowError("Frequency", RowName, frm); ThrowErrorFlag = true; break; } } if(!ThrowErrorFlag) removeErrorFormatting(ElmtName, RowName, frm); } function CheckTextArea(field, maxlen) { if (field.value.length > maxlen) { field.value = field.value.substring(0, maxlen); alert('Only 1000 characters allowed. Your input has been truncated to 1000 characters'); } } //------ function ThrowError(ElmtName, RowName, frm) { if(!eval("document.getElementById('" + RowName + "')")) return; applyErrorFormatting(ElmtName, RowName,frm) error[error.length] = RowName; } //------ function applyErrorFormatting(fldName, RowName,frm) { tableRow = eval("document.getElementById('" + RowName + "')"); tableRow.className = "error2"; } //----- function removeErrorFormatting(fldName, RowName,frm) { var isSharedRow = CheckForSharedRow(RowName) // call function to handle fields that share the same row if(isSharedRow) return true; tableRow = eval("document.getElementById('" + RowName + "')"); if(tableRow) tableRow.className = "quoter"; } function CheckForSharedRow(RowName) { for(var i=0;i<error.length;i++) { if(error[i] == RowName) return true; } return false; } function isBrowserCompatible() { if(document.getElementById) return true; else return false; } function trim(str) { return str.replace(/^\s*|\s*$/g,""); } //------ function OpenWindow(name,filename,height,width,parameters) { var hwin = window.open(filename,name,"height=" + height + ",width=" + width + "," + parameters); hwin.focus(); } //----- function StandardPopup(pagePath) { OpenWindow("", pagePath, 450, 300, ""); } //------ Code for the form: Code: <form action="#" method="get" onsubmit="return ValidateQuoteRequest(this);" name="FrontPage_Form"> <tr class="quoter" id="row_state"> <td align="right" nowrap=""><a href="javascript:popUp('state')" title="">State</a></td> <td colspan="2"> <select name="state" size="1" tabindex="12"> <option value="-1">Select state...</option> <option value="AK">Alaska</option> </select> </td> </tr> <tr class="quoter" id="row_date"> <td align="right"><a href="javascript:popUp('dob');" title="">Date of Birth</a></td> <td colspan="2"><select name="Month"> <option value="-1">Month</option> <option value="01">Jan</option> </select> <select name="Day"> <option value="-1">Day</option> <option value="01">01</option> </select> <select name="Year" size="1"> <option value="-1">Year</option> <option value="1921">1921</option> </select> </td> </tr> <tr class="quoter" id="row_sex"> <td align="right"><a href="javascript:popUp('gender')" title="">Gender</a></td> <td colspan="2"><select name="Sex" size="1"> <option value="-1">Select...</option> <option value="1">Male</option> </select> </td> </tr> <tr class="quoter" id="row_Height"> <td align="right">Height</td> <td nowrap="" colspan="2"><select name="Height_Feet" size="1"> <option value="-1"></option> </select> ft <select name="Height_Inches" size="1"> <option value="-1"></option> </select> in Weight <input name="Weight" size="3" maxlength="3" value=""> lbs </td> </tr> <tr class="quoter" id="row_tobacco"> <td align="right"><a href="javascript:popUp('tobacco')" title="">Tobacco/ Nicotine Use</a></td> <td colspan="2"><select name="Tobacco" onchange="toggleRow(this,'4,5,6,7,8','row_tobaccotype',document.FrontPage_Form.Frequency)"> <option value="-1">Select...</option> <option value="1">Never used</option> <option value="7">Current user</option> </select></td> </tr> <tr class="quoter" style="display: none; " id="row_tobaccotype"> <td align="right">Type of Tobacco or Nicotine and frequency of use</td> <td colspan="2"><select name="Frequency"> <option value="0" selected="">Please select...</option> <option value="10">Cigarettes, less than 1/2 pack a day</option> </select></td> </tr> <tr class="quoter" id="row_coverage"> <td align="right" class="quoter"><a href="javascript:popUp('calculator','https');" title="">Coverage Amount</a></td> <td><select name="Amount" size="1"> <option value="750000">$750,000</option> </select> <a href="javascript:popUp('calculator');" title="" class="nav-sub" ;=""><img src="./Insurance_files/help.gif" width="16" height="17" alt="" border="0" align="bottom"></a></td><td class="quoter"><a href="javascript:popUp('calculator');" title="">How much life<br>insurance do I need?</a></td> </tr> <tr class="quoter"> <td align="right"><a href="javascript:popUp('term');" title="">Guaranteed Term</a></td> <td class="quoter" colspan="2" id="ProductType"><select name="ProductType" size="1"> <option value="8">10 Years</option> </select></td> </tr> <tr class="quoter" id="row_PreClass"> <td align="right"><a href="javascript:popUp('healthclass');" title="">Health Class</a></td> <td><select name="PreClass" size="1"> <option value="0" selected="">Best Class</option> <option value="2">Preferred</option> </select> <a href="javascript:popUp('healthclass');" title=""><img src="./Insurance_files/help.gif" width="16" height="17" alt="" border="0" align="bottom"></a></td> <td><a href="javascript:popUp('healthclass');" title="">How do I determine<br>my health class?</a><a href="#">*</a></td> </tr> <tr class="quoter" id="row_firstname"> <td align="right"> First Name</td> <td class="quoter" colspan="2"><input name="firstname" size="30" maxlength="50" value=""></td> </tr> <tr class="quoter" id="row_lastname"> <td align="right"> Last Name</td> <td colspan="2"><input name="lastname" size="30" maxlength="50" value=""></td> </tr> <tr class="quoter" id="row_workphone"> <td align="right">Social Security Number</td> <td colspan="2">(<input maxlength="3" name="ssn1" size="3" value="">)-<input maxlength="2" name="ssn2" size="2" value="">-<input name="ssn3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_workphone"> <td align="right">Work Phone</td> <td colspan="2">(<input maxlength="3" name="workphone1" size="3" value="">)-<input maxlength="3" name="workphone2" size="3" value="">-<input name="workphone3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_homephone"> <td align="right">Home Phone</td> <td colspan="2">(<input maxlength="3" name="homephone1" size="3" value="">)-<input maxlength="3" name="homephone2" size="3" value="">-<input name="homephone3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_email"> <td align="right"><a href="javascript:popUp('email','https');">E-mail</a></td> <td colspan="2"><input name="email" size="30" maxlength="80" value=""></td> </tr> <tr> <td colspan="3" align="center" nowrap=""> <input type="image" title="Please click only once." name="Submit" src="./Insurance_files/compare_rates.gif" width="172" height="28" value="Compare Rates Now!" alt="Get Your Life Insurance Quote Now"> </form> I have a form developed in Dreamweaver CS5 using Spry Assets, I have 2 required fields in the form. One is email the other is phone. I want the user to only have to fill in one or the other, but one or the other needs to be filled out. Here is the form code: [code]<form id="form1" name="form1" method="post" action="http://www.greenhousegraphix.com/GatewayVentures/sendmail.php"> <span id="sprytextfield1"><label>Name</label> <input name="Name" type="text" id="Name" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span></span><br /> <span id="sprytextfield3"><label>Title</label> <input name="Title" type="text" id="Title" size="45" /> </span><br /> <span id="sprytextfield2"><label>Company</label> <input name="Company" type="text" id="Company" size="45" /> </span><br /> <span id="sprytextarea1"><label>Address</label> <textarea name="Address" id="Address" cols="39" rows="2"></textarea> </span><br /> <span id="sprytextfield4"><label>City</label> <input name="City" type="text" id="City" size="45" /> </span><br /> <span id="sprytextfield5"><label>State</label> <input name="State" type="text" id="State" size="45" /> </span><br /> <span id="sprytextfield6"><label>Zip</label> <input name="Zip" type="text" id="Zip" size="45" /> <span class="textfieldInvalidFormatMsg">Invalid format.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMinValueMsg">The entered value is less than the minimum required.</span></span><br /> <span id="sprytextfield7"><label>Phone</label> <input name="Phone" type="text" id="Phone" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextfield8"><label>Email</label> <input name="Email" type="text" id="Email" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextarea2"><label>Message</label> <textarea name="Message" id="Message" cols="39" rows="6"></textarea> </span><br /> <input name="SUBMIT" type="image" class="marginleft95px" src="images/submit.jpg" /> </form> </div> <div id="apDiv2"><img src="images/contact-us-keyboard.jpg" width="318" height="230" alt="contact us" /></div> <div id="apDiv3"><img src="images/contact-us.jpg" width="318" height="230" alt="contact us" /></div> </div></div> <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["blur"]}); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {isRequired:false}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none", {isRequired:false}); var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none", {isRequired:false}); var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5", "none", {isRequired:false}); var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6", "zip_code", {isRequired:false}); var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7", "phone_number", {validateOn:["blur"], hint:"(999) 999-9999"}); var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8", "email", {validateOn:["blur"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {isRequired:false}); var sprytextarea2 = new Spry.Widget.ValidationTextarea("sprytextarea2", {isRequired:false}); </script>[code] Please help!! I have problem with my javascript form validation... Validation works only on last question and I can't understand why it doesn't work on other questions.. Html code : 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> <script type="text/javascript" src="script.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Questionaire</title> <link href="oneColLiqCtrHdr19.css" rel="stylesheet" type="text/css" /> <style type="text/css"> <!-- body { background-color: #FFF; background-image: url(images/aa.jpg); } --> </style></head> <body class="oneColLiqCtrHdr"> <div id="container"> <div id="header"> <h1> </h1></div> <!-- forms --> <form action="http://projects.knord.dk/interaction/saveforminfo.aspx" method="post" onsubmit="return checkform(this);" > <input type="hidden" name="surveyid" value="knjuku2" /> <input type="hidden" name="usecookie" value="true" /> <input type="hidden" name="landingpage" value="h---.html" /> <p align="center"><b>This survey was made for Business Academy Copenhagen North project not for FDIM.</b></p> <p> <b>Please enter your personal information</b> </p> <p><b>Your Occupation:</b> <input type="text" name="occupation" /> </p> <p><b>Age Group:</b> <select name="age"> <option value="under 18">less then 18</option> <option value="18-25">18-25</option> <option value="26-35">26-35</option> <option value="over 35">more then 35</option> </select> </p> <p><b>Status:</b> <select name="status"> <option value="single">Single</option> <option value="single with children">Single with children</option> <option value="in relationship">In relationship</option> <option value="married">Married</option> <option value="divorced">Divorced</option> </select> </p> <p><b>Gender:</b> <input type="radio" name="gender" value="male" /> Male <input type="radio" name="gender" value="female" /> Female </p> <p><b>Do you have a job?</b> <input type="radio" name="job" value="yes" />Yes <input type="radio" name="job" value="no" />No </p> <p> </p> <p> <!-- 1 vopros --> </p> <p><b>1. Why do You use online social media?</b> </p> <p> <input type="radio" name="bla" value="To chat with friends" /> To chat with friends<br></br> <input type="radio" name="bla" value="To read news" /> To read news<br></br> <input type="radio" name="bla" value="To write blogs" /> To write blogs<br></br> <input type="radio" name="bla" value="Other" /> Other<br></br> </p> <p> <!-- 2 vopros --> <b>2. What online social media do You use more often?</b> </p> <p> </p> <p> <select name="more"> <option value="MySpace">MySpace</option> <option value="Twitter">Twitter</option> <option value="Facebook">Facebook</option> <option value="LinkedIn">LinkedIn</option> </select> </p> <p> </p> <!-- 3 vopros --> <b>3. When do You use it?</b> <p> <input type="radio" name="use" value="1" /> At home<br></br> <input type="radio" name="use" value="2" /> At work<br></br> <input type="radio" name="use" value="3" /> At school<br></br> <input type="radio" name="iuse" value="4" /> In the bus/train<br></br> <input type="radio" name="use" value="5" /> Other<br></br> </p> <p><b>4. How much hours approximately do You spend on social media?</b> </p> <select name="hours"> <option value="less than 2 hours">less than 2 hours a day</option> <option value="2-4 hours">2-4 hours a day</option> <option value="4-8 hours">4-8 hours a day</option> <option value="8-12 hours">8-12 hours a day</option> <option value="more than 12 hours">more than 12 hours a day</option> </select> <p> </p> <p> <!-- 5 vopros --> <b>5. Do You use social media often?</b></p> <p> <input type="radio" name="often" value="Yes" /> Yes <input type="radio" name="often" value="No" /> No <!-- 6 vopros --> </p> <p><b>6. Social Media website to which You usually upload</b></p> <p> <input type="radio" name="upload" value="Youtube" /> Youtube<br></br> <input type="radio" name="upload" value="Flickr" /> Flickr<br></br> <input type="radio" name="upload" value="Photobucket" /> Photobucket<br></br> <input type="radio" name="upload" value="Slideshare" /> Slideshare<br></br> <input type="radio" name="upload" value="Other" /> Other </p> <!-- 7 vopros --> <b>7. Where do You chat with Your friends</b> <select name="chatting"> <option value="Msn">Msn</option> <option value="Skype">Skype</option> <option value="Yahoo!">Yahoo!</option> <option value="Other">Other</option> </select> <p> </p> <!-- 8 vopros --> <b>8. You use social media for</b> <select name="using"> <option value="Personal reasons">Personal reasons</option> <option value="Professional reasons">Professional reasons</option> <option value="Don't use it">Don't use it</option> </select> <p> </p> <p> <!-- 9 vopros --> <b>9. You prefer to obtain the information You need at</b> <select name="information"> <option value="Yahoo!">Yahoo!</option> <option value="Google">Google</option> <option value="Wikipedia">Wikipedia</option> <option value="Ask">Ask</option> <option value="Other">Other</option> </select> </p> <!-- 10 vopros --> <b>10. What do You prefer to do being online</b>? <select id="drop" name="online"> <option value="Read blogs">Read blogs</option> <option value="Chat with friends">Chat with friends</option> <option value="Watch videos">Watch videos</option> <option value="Read news">Read news</option> <option value="Other">Other</option> </select> <!-- konec voprosov --> <!-- button-submit --> <p align="center"> <input type="submit" value="Submit" /> </p> </form> <!-- end #container --> </div> </body> </html> Javascript validation Code: //Javascript Document function checkform ( form ) { if (form.occupation.value == "") { alert( "Please enter your occupation." ); form.occupation.focus(); return false ; } return true ; } function checkform(f) { for (var i=0; i<f.elements("gender").length; i++) { var radio = f.elements("gender")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Choose your gender!"); f.elements("gender")[0].focus(); return false; } function checkform(f) { for (var i=0; i<f.elements("job").length; i++) { var radio = f.elements("job")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Choose if you have a job!"); f.elements("job")[0].focus(); return false; } function checkform(f) { for (var i=0; i<f.elements("bla").length; i++) { var radio = f.elements("bla")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Answer question number 1"); f.elements("bla")[0].focus(); return false; } function checkform(f) { for (var i=0; i<f.elements("use").length; i++) { var radio = f.elements("use")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Answer question number 3!"); f.elements("use")[0].focus(); return false; } function checkform(f) { for (var i=0; i<f.elements("often").length; i++) { var radio = f.elements("often")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Answer question number 5!"); f.elements("often")[0].focus(); return false; } function checkform(f) { for (var i=0; i<f.elements("upload").length; i++) { var radio = f.elements("upload")[i]; if (radio.checked) { return true; } } // no checked radio button found window.alert("Answer question number 6!"); f.elements("upload")[0].focus(); return false; } Where is my mistake? And how to solve it to make javascript validation work properly? Hi there! Could somebody please help me understand why this javascript isn't executing? I've been stuck with it for days and have researched the problem to death to no avail. Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Form</title> <script type="text/javascript"> function allComplete() { var result = true; var numbers = document.getElementsById('numbers'); for(var number in numbers) { if(number.value == null) { result = false; break; } } if(result == false) { alert("Please fill in all the fields"); return result; } return result; } </script> </head> <body> <h3>In each field enter a number of your choice!</h3> <form action="php.php" method="GET"> <input type="text" name="numbers[]" id="numbers" size="4" /><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="submit" name="submit" onSubmit="return allComplete()" value="Enter"/><br/> </form> </body> </html> Thanks very much in advance. Hi Guys, I have trying to validate my form using JavaScript. On blur of the a text box I am calling a function in JavaScript which checks if the text box is empty or not.... If the text box is empty it display an appropriate error message. The issue I am facing is that, for the first time if any user does not enter any value in the text box, the JS function is invoked and an appropriate error message is displayed.... So when the user tried to enter a value in the text box, a drop down list appear from the past forms data. (The drop down value appear because the user has already filled in the form in the past. Hence the Browser remember the data filed in, and displays it as a drop down list.) This allows the user to select any values from the drop down list to fill in the box.* After the user has selected the appropriate value from the drop down and takes its mouse cursor and navigates to another text box in the form, the first error message does not disappear. The form does not recognize that the value filed has already been filled in the first filed.* If the user actually types into the field it recognizes that the text box has a filed is filled. Please may I know how to solve this issue. Hello, I am using the following javascript to validate a text field on my site: Code: function checkExpire(form) { // regular expression to match required date format re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if(form.txtExpire.value != '' && !form.txtExpire.value.match(re)) { alert("Invalid date format: " + form.txtExpire.value); form.txtExpire.focus(); return false; } return true; } The above code works fine for the following situations: The default value of the field is: __/__/____ The JavaScript code above will not accept that for a field value. If a user inputs the following for a date 5_/7_/11__ for May 7th, 2011 the JavaScript will not accept the format it must be entered as: 05/07/2011 (in order to clear the validation)... NOW HERE IS WHAT I NEED THE JAVASCRIPT TO DO: 1) It needs to accept __/__/____ as a value that can be inserted into the database 2) still retains the code above so 5_/7_/11__ is not an acceptable date but 05/07/2011 will work just fine 3) Now... the default value of the text field in Internet Explorer is __/__/____ but the value is blank in Mozilla Firefox so in an instance where the text field is completely blank I need the JavaScript to assign the value '__/__/____' ... SO FAR: I did at one point get both the validation working so it worked for rules 1 and 2 mentioned above but I completely destroyed it while trying to integrate rule 3 into the functionality. So I know this can be accomplished with a series of if / else statements as well as assigning a value to a form object to handle rule# 3 ... I am just a novice getting ready to turn intermediate in JavaScript so any help, guidance, reference or example / sample code you could give me would be much appreciated. Thank your for your assitance and I hope you are all doing well. Cordially, aRK I have a simple form and am validating onchange and need a final validation onsubmit. I am displaying a message to the right of the inputbox on error. I'm trying to keep this at DOM 1 compatible and not use any framework. HTML Code: <form id = "myForm" action = "" onsubmit = "return validateForm(this);"> <table class = "table-submit" border = "0"> <tr> <td> Username: </td> <td> <input type = "text" id = "username" size = "30" maxlength = "30" onchange = "validateUsername(this, 'msgUsername')" /> </td> <td id = "msgUsername"> </td> </tr> <tr> <td> Password: </td> <td> <input type = "password" id = "password" size = "30" maxlength = "30" onchange = "validatePassword(this, 'msgPassword')" /> </td> <td id = "msgPassword"> </td> </tr> <tr> <td> </td> <td> <input type = "submit" value = "Submit" /> <input type = "reset" value = "Clear" /> </td> </tr> </table> </form> JavaScript Code: function validateUsername(myItem, myElement) { var dom = document.getElementById(myElement); if (myItem.value.length < 3) { dom.innerHTML = " Username needs to be a minimum of 3 characters! "; return false; } else { dom.innerHTML = ""; return true; } } function validatePassword(myItem, myElement) { var dom = document.getElementById(myElement); if (myItem.value.length < 5) { dom.innerHTML = " Password needs to be a minimum of 5 characters! "; return false; } else { dom.innerHTML = ""; return true; } } function validateForm (itm) { // kind of stuck here... } As you may of noticed, I am a bit stuck on my validateForm() function. The code validates on each inputbox onchange event. Not sure what is the best way to go from here. I thought about doing an If for my both single input box validation, but I would need to send each parameters which is what i was trying to avoid by using this. Would like some suggestions. Hello there, I hope you might be able to help me with an issue I'm having getting a form to validate before submission. I've been trying to figure out where I'm going wrong but being relatively new to javascript I'm obviously missing something. I have a form which calls one of two validation scripts with onBlur for each field (I've only included one of each field, there are 8 fields in total in the form): Code: <form name="submitrunnertime" action="http://......reflect.php" onsubmit="return valResultsForm();" method="post"> <table> <tr><td><label for="RunnerID">Runner ID</label></td> <td><input type="text" name="RunnerID" size="5" maxlength="5" onBlur="valRange(RunnerID, 1, 99999, 'RunnerID_bk');" /> </td><td id="RunnerID_bk"><span></span></td></tr> <tr><td><label for="">Date (YYYY-MM-DD)</label></td> <td><input type="text" name="Date" size="10" maxlength="10" onBlur="valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format');" /> </td><td id="Date_bk"><span></span></td></tr> etc. etc. </table> <input type="submit" name="submitrunnertime" value="submit"> </form> I've managed to get each individual field to validate as the form is filled in. Now, if I fill valResultsForm.js with a simple line return false; then the form refuses to submit as it should do, but if I try and re-run the validation of each field so that the form will only submit if all fields have been filled in correctly, even if I force valResultsForm to return a false result, the form still submits. I just can't figure out why it is doing this and it's driving me around the bend. valResultsForm looks like: Code: function valResultsForm() { var res1 = valRange(RunnerID, 1, 99999, 'RunnerID_bk'); var res2 = valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format'); if (res1 == true && res2 == true) { return true; } else { return false; } } Any hints or advice that anyone could give me would be hugely appreciated. Thank you, Andrew Below is some code I wrote for my assignment that is due tonight; however, I can't seem to get any of the validation features to work. Can someone help me? I'm really new to javascript and struggling through it, but really want to figure this out. Here are the things I'm trying to do: -Validate each textbox to make sure they aren't empty -Validate one textbox to make sure that the text entered is numeric only -Validate the two email addresses for proper email format -Validate the two email addresses to make sure they are exactly alike -Show all of your errors at once, in one alert box, not individually. -Only check for matching emails if the first is valid. Here is my attempt at the code: [CODE] <script type="text/javascript"> <!-- Hide from older browsers var ProductInquiryForm; function Validate( ProductInquiryForm ) { formName = ProductInquiryForm; } function ValidEmail( EmailSearch ) { var txtEmail = EmailSearch.value; var intAtSign = txtEmail.indexOf("@"); var intLastDot = txtEmail.lastIndexOf("."); if( txtEmail == "" || txtEmail == null ) { return false; } if( intAtSign == -1 || intLastDot == -1 ) { return false; } if( intLastDot < intAtSign ) { return false; } if( intLastDot - intAtSign == 1 ) { return false; } if( intLastDot >= txtEmail.length-2 ) { return false; } else { return true; } } function ValidEmail( ConfirmEmailSearch ) { var txtEmail = ConfirmEmailSearch.value; var intAtSign = txtEmail.indexOf("@"); var intLastDot = txtEmail.lastIndexOf("."); if( txtEmail == "" || txtEmail == null ) { return false; } if( intAtSign == -1 || intLastDot == -1 ) { return false; } if( intLastDot < intAtSign ) { return false; } if( intLastDot - intAtSign == 1 ) { return false; } if( intLastDot >= txtEmail.length-2 ) { return false; } if (EmailSearch!= ConfirmEmailSearch) { return false; } else { return true; } } function ApprovedEmail ( ConfirmEmailSearch ) { if( HasText(EmailSearch) && ValidEmail(EmailSearch) && HasText(ConfirmEmailSearch) && ValidEmail(ConfirmEmailSearch)) { return true; } else { alert("A valid email must be entered and match in both fields!"); return false; } } function validateZIP(ZIPSearch) { if( ZIPSearch.value != 0||1||2||3||4||5||6||7||8||9) { alert("Please enter digits only for the ZIP code."); return false; } if (field.length!=5) { alert("Please enter no more than 5 digits for your ZIP code."); return false; } function HasText( ProductSearchDescription ) { if( ProductSearchDescription.value.length != 0 ) { return true; } else { alert("Please enter your product needs."); return false; } } // Stop hiding --> </script> <noscript> This site uses JavaScript code for validation and calculations based on user input. </noscript> <form name="form1" id="form1" method="post" action="intercept-searchform.asp" onsubmit="return Validate(this)"> <div> <label for="EmailSearch">Email Address:</label> <input name="EmailSearch" type="text" class="TextBox" id="EmailSearch" /> </div> <div> <label for="ConfirmEmailSearch">Confirm Email Address:</label> <input name="ConfirmEmailSearch" type="text" class="TextBox" id="ConfirmEmailSearch" /> </div> <div> <label for="ZIPSearch">ZIP Code</label> <input name="ZIPSearch" type="zip" class="zip" id="zip" /> </div> <div> <label for="ProductSearchDescription">Describe the product you are looking for.</label> <textarea name="ProductSearchDescription" id="ProductSearchDescription" class= "Comments" rows="6" cols="50"></textarea> </div> <br /> <div id="buttons"> <input name="Submit" type="Submit" value="Submit" /> <input name="Reset" type="Reset" /> </div> </form> [CODE] Thank you so much to anyone willing to help give me some guidance! Hello, Am new to this forum, as you can see this is my first post. Am having problem in validating my form, so i like you guys to help me out. Code: <html> <head> <title>Javascript form Validation</title> <script language="javascript"> <!-- function formValid() { var user = ducument.getElementById('userid'); var email = document.getElementById('emailid'); var select = document.getElementById('selection'); if(check_restrict(user,6,10)){ if(check_email(email,'Invalid Email address')){ if(check_select(select,'Please make a selection')){ return true; } } } return false; } function check_restrict(elem,min,max){ if(elem.value.length >= min && elem.value.length <= max){ return true; } else{ alert("Please enter " +min+ " to " +max+ "character") elem.focus(); return false; } } function check_email(elem,helperMsg){ var emailExp = /^[a-z0-9A-Z\.\-\_]+\@[a-zA-Z\-\.]+\.[a-zA-Z\.]{2,3}$/; if(elem.value.match(emailExp)){ return true; } else{ alert(helperMsg) elem.focus(); return false; } } function check_select(elem,helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg) elem.focus(); return false; } else{ return true; } } //--> </script> </head> <body> <form name="f1" onsubmit="return formValid()"> Username(6-10):<input type="text" id="userid" size=10 maxlength="15"><br/> Email Address:<input type="text" id="emailid" size=20 maxlength="20"><br/> <select id="selection"> <option>Please Choose</option> <option>Login</option> <option>Register</option> </select><br/> <input type="submit" value="Submit"> </form> </body> </html> Any help we be appreciated. Regards. Hiya, Got a form located at the following link: http://www.boostcreative.com/MA/ In short, trying to make it so that the user can type multiple numbers into the various fields and in real time they add up. If it hits the magic number, they can submit the form. The problem I'm having is the form validation. Any thoughts as to how I would set it so that the form is only submitted if the magic number is reached? (In this case 200) Thanks! Code: $(document).ready(function(){ $(".addition").each(function() { $(this).keyup(function(){ calculateSum(); }); }); }); function calculateSum() { var sum = 0; $(".addition").each(function() { if(!isNaN(this.value) && this.value.length!=0) { sum += parseFloat(this.value); if ( sum == 200 ) { $('#negative').hide();$('#positive').show();} if ( sum != 200 ) { $('#negative').show();$('#positive').hide();} } }); $("#sum").html(sum.toFixed(0)); } function validateForm() { var total = 0; $(".addition").each(function() { if(!isNaN(this.value) && this.value.length!=0) { total += parseFloat(this.value); if ( total != 200 ) { alert("That Total is incorrect"); return false; } } Code: <form method="post" action="contactForm.php" name="MAloyalty" id="MAloyalty" onsubmit="return validateForm(this)" > I need help with a JavaScript form validation code. I am using the form validation code that is found on this page: http://www.dynamicdrive.com/dynamici...uiredcheck.htm The code works fine for me, but what I'm trying to do is add an additional condition to it. Currently, I just have the code set up to check if the user has enter their name, email, and phone number. But I also need it to validate something else only if a specific condition is true. On my form I have 2 different sets of Radio lists. One is called Function and the other radio list is called Design. If the user selects an option on one of the 2 lists, then it will be required for the user to also select an option from the 2nd list. The user CAN decide not to select anything from either radio list, but can not select from one list and NOT from the other. This is the If statement that I created (don't know if its correct or how to insert it to my current validation code). Code: <script type="text/javascript"> if (Function+Design<1 or == 400 or == 800) {document.write("Please select both a Function and Design Type");} </script> Hello: I am using javascript validation for submitting a form. All the other fields are working except for the Terms of Use checkbox. It sends and alert and says it wasn't checked whether or not you check it. It also submits the form whether or not it is checked immediately after the alert. The field is called df_Terms. Can anyone see anything I am missing? Code: <script> //submit after validation functionality function submit_onclick() { var proceed = false; if (typeof validateForm == "function") { proceed = validateForm(); } else { proceed = true; } return proceed; } //validation functionality function validateForm() { if ((document.form1.df_Plans[0].checked == false) && (document.form1.df_Plans[1].checked == false)) { alert("Please select Your Plan"); document.form1.df_Plans[0].focus(); return false; } if ("" == document.form1.df_first_Name1.value) { alert("Please enter your First Name"); document.form1.df_first_Name1.focus(); return false; } if ("" == document.form1.df_last_Name1.value) { alert("Please enter your Last Name."); document.form1.df_last_Name1.focus(); return false; } if ("" == document.form1.df_email1.value) { alert("Please enter your email."); document.form1.df_email1.focus(); return false; } validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i; strEmail = document.form1.df_email1.value; if (strEmail.search(validRegExp) == -1) { alert("A valid e-mail address is required."); document.form1.df_email1.focus(); return false; } if (!document.form1.df_Terms.checked == 1) { alert("Please agree to the Terms of Use."); document.form1.df_Terms.focus(); return false; } } //reset field functionality function reset_onclick() { for (i = 0; i < document.form1.elements.length; i++) { if (document.form1.elements[i].type == "text") { document.form1.elements[i].value = ""; } if (document.form1.elements[i].type == "checkbox") { document.form1.elements[i].checked = false; } if (document.form1.elements[i].type == "radio") { document.form1.elements[i].checked = false; } if (document.form1.elements[i].type == "select-one") { document.form1.elements[i].selectedIndex = 0; } } } //redirect functionality function redirect_onclick(urlString) { window.open("http://" + urlString); } </script> I'm trying to do a simple validation to see if the field is blank, if it is, I want to write a message to a div. I've added the function call to an onclick. It seems to be set off no matter if there is a value or not, and what's more, the fields are clearing out when the link is clicked. My brain is mush right now, so what am I missing? Code: function validateThis() { document.getElementById('messages').innerHTML = '' var theMessage = ''; var reqMsg = 'must have a value.'; for (var i = 0; i <document.theForm1.elements.length; i++) { if (document.theForm1.elements[i].value = ' ') { theMessage += document.theForm1.elements[i].name +' ' + reqMsg +'<br/>'; }} document.getElementById('messages').innerHTML = theMessage; } Hi I am trying to write a simple script for html form validation before going on to write a more complicated script for the full form which will eventually be on the web page. However, I cannot tell if the javascript is executing or not, as no alert messages come up. If I fill in the form with blanks (which is what the function checkform() checks for) then it should display an alert on submission and return false. Otherwise, returns true. I need to get this licked before going on to the more complex coding, but I really can't see why this doesn't appear to work. I'd be most grateful if some kind soul out there could have a look at it for me.... Links below. Thank you in anticipation! http://www.kellyresources.co.uk/onli...ment_test.html http://www.kellyresources.co.uk/checkform.js I'm trying to output something in a separate div if the information entered in the form is invalid. It is simply not working, no errors. Code: <script type="text/javascript" language="javascript"> function validateIGN(ign) { var validign = /^[a-zA-Z0-9]{1,30}$/; if (!validign.test(ign)) { document.getElementById.ignErrors.innerHTML = "<p>Your IGN is not formatted properly."; } else { } } </script> Heres the HTML where the onkeyup is.. Code: <form name= "newsletter" class="newsletter" action="doNewsletter.php" method="post"> <h2>Fill out this form if you want to be notified when the website is up!</h2><br/> <center><table class="twoslot"> <tr> <td>IGN(In Game Name):</td><td><input type="text" name="ign" onkeyup="return validateIGN(newsletter.ign.value);" /></td> </tr> <br/> <tr> <td>E-mail:</td><td><input type="text" name="email" /></td> </tr> <br/> <tr> <td> <center> <input type="submit" value="Submit" /> </center> </td> </tr> </table></center> <span style="font-size: .5em;">This is not working yet</span> </form> |