JavaScript - Is Javascript The Effective One To Do Validation?
hi friends,
I have a question with me is javascript is the effective one to do validation? And how it can be used for validation purposes.. Similar TutorialsI have a validation issue. I need the input fields to highlight yellow if no text has been entered and when the form is submitted the error message displays to check the highlighted fields. I get the input boxes to highlight when there is no text but on submit the form goes to the next page without the error alert message. Any suggestions would be appreciated. My HTML page: Code: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- Filename: works.htm Supporting files: --> <!-- #BeginEditable "doctitle" --> <title>Wizard Works Order Form</title> <!-- #EndEditable --> <link href="ww.css" rel="stylesheet" type="text/css" /> <script src="functions.js" type="text/javascript"></script> <script src="valid.js" type="text/javascript"></script> </head> <body> <form id="order" action="file:///F:/JavaScript/case4/done.htm" onsubmit="return validateForm()" method="post"> <div id="page"> <div id="head"> <img alt="Wizard Works" src="logo.jpg" /> </div> <ul id="links"> <li><a href="#">Home</a></li> <li><a href="#">Assortments</a></li> <li><a href="#">Firecrackers</a></li> <li><a href="#">Fontains</a></li> <li><a href="#">Cones</a></li> <li><a href="#">Rockets</a></li> <li><a href="#">Sparklers</a></li> <li><a href="#">Online Store</a></li> <li><a href="#">Shopping Cart</a></li> <li><a href="#">Your Account</a></li> <li><a href="#">Safety</a></li> <li><a href="#">Tech Support</a></li> <li><a href="#">Customer Service</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Contact Us</a></li> </ul> <div id="webform"> <fieldset id="purchase"> <legend>Order</legend> <label id="produtLab" class="required" for="product">1) Product</label> <select id="product"> <option value="">Select a Product</option> <option value="3.5">Green/Purple Fountain: $3.50 ea.</option> <option value="4.95">Silver Cone: $4.95 ea.</option> <option value="6.95">Glitter Cone: $6.95 ea.</option> <option value="9.95">Glittering Stars: $9.95 ea.</option> <option value="19.95">Fountain Kit: $19.95 ea.</option> <option value="29.95">Fountain Kit Deluxe: $29.95</option> <option value="39.95">Giant Fountain: $39.95</option> </select> <br /> <label id="qtyLab" class="required" for="qty">2) Quantity</label> <select id="qty"> <option value="">Select a Quantity</option> <option value="1"> 1</option> <option value="2"> 2</option> <option value="3"> 3</option> <option value="4"> 4</option> <option value="5"> 5</option> <option value="6"> 6</option> <option value="7"> 7</option> <option value="8"> 8</option> <option value="9"> 9</option> <option value="10">10</option> </select> <br /> <label id="shippingLab" class="required" for="shipping">2) Shipping</label> <select id="shipping"> <option value="">Select a Shipping Option</option> <option value="4.95">Standard ($4.95)</option> <option value="8.95">Express ($8.95)</option> <option value="12.95">Next Day ($12.95)</option> </select> <br /> <label id="totalLab" for="total">3) Total Calculated Cost</label> <input id="total" readonly="readonly" size="20" type="text" /> </fieldset> <fieldset id="contact"> <legend>Contact Information</legend> <label id="fnameLab" class="required" for="fname">4) First Name</label> <input id="fname" size="20" type="text" class="validate" onblur="changeColor(this)" /> <br /> <label id="lnameLab" class="required" for="lname">5) Last Name</label> <input id="lname" size="20" type="text" onblur="changeColor(this)" /> <br /> <label id="addressLab" class="required" for="address">6) Address</label> <textarea id="address" cols="20" rows="5"onblur="changeColor(this)" ></textarea> <br /> <label id="phoneLab" class="required" for="phone">7) Phone (nnn) nnn - nnnn</label> <input id="phone" size="20" type="text" onblur="changeColor(this)" /> </fieldset> <fieldset id="credit"> <legend>Payment Information</legend> <label for="ccard">8) Credit Card</label> <select id="ccard"> <option value="ae">American Express</option> <option value="dc">Diners Club</option> <option value="disc">Discover</option> <option value="mc">MasterCard</option> <option value="visa">Visa</option> </select> <br /> <label id="cholderLab" class="required" for="cholder">9) Card Holder</label> <input id="cholder" size="20" type="text"onblur="changeColor(this)" /> <br /> <label id="cnumLab" class="required" for="cnum">10) Card Number</label> <input id="cnum" size="20" type="text"onblur="changeColor(this)" /> <br /> <label class="required">11) Expiration Date</label> <select id="cmonth" name="cmonth"> <option>01</option><option>02</option><option>03</option> <option>04</option><option>05</option><option>06</option> <option>07</option><option>08</option><option>09</option> <option>10</option><option>11</option><option>12</option> </select> / <select id="cyear" name="cyear"> <option>2010</option><option>2011</option><option>2012</option> <option>2013</option><option>2014</option><option>2015</option> </select> </fieldset> <input id="sbutton" type="submit" value="Submit Order" onclick="returm validateForm();return false;"/> </div> </div> </form> </body> </html> My valid.js code: Code: /* Functions List: initForm() Initiates the Web form for use by the customer calcCost() Calculates the cost of the customer order validLengths() Validates that empty values have been entered for required fields testLength(field) Tests the length of the text string in the specified field validPatterns() Validates that the field values match their regular expressions testPattern(field, reg) Tests a text string against a specified regular expression validCNum() Tests that the specified credit card number passes the Luhn formula validateForm() Performs a validation test on all of the fields in the form */ window.onload = initForm; var wform; var productIndex = 1; var qtyIndex = 1; var shipIndex = 1; function initForm() { wform = document.forms[0]; wform.product.onchange = calcCost; wform.qty.onchange = calcCost; wform.shipping.onchange = calcCost; wform.onsubmit = validateForm; } function calcCost() { productIndex = wform.product.selectedIndex; productCost = parseFloat(wform.product.options[productIndex].value); qtyIndex = wform.qty.selectedIndex; qtyVal = parseFloat(wform.qty.options[qtyIndex].value); shipIndex = wform.shipping.selectedIndex; shipVal = parseFloat(wform.shipping.options[shipIndex].value); if (productIndex != 0 && qtyIndex != 0 && shipIndex != 0) { wform.total.value = "$"+(productCost*qtyVal+shipVal).toFixed(2); } } function validLengths() { var isValid = true; if (testLength(wform.total)== false) isValid = false; if (testLength(wform.fname)== false) isValid = false; if (testLength(wform.lname)== false) isValid=false; if (testLength(wform.address)== false) isValid=false; if (testLength(wform.phone)== false) isValid=false; if (testLength(wform.cholder)== false) isValid=false; if (testLength(wform.cnum)== false) isValid=false; return isValid; } function testLength(field) { var isValid = true; if (field.value.length == 0) { document.getElementById(field.id+"contact").style.bgcolor="yellow"; isValid = false; } else { document.getElementById(field.id+"contact").style.bgcolor="white"; } return isValid; } function validPatterns() { var isValid = true; phonereg = /^\(?\d{3}[\)-]?\s?\d{3}[\s-]?\d{4}$/; if (testPattern(wform.phone, phonereg) == false) isValid = false; creditType = wform.ccard.selectedIndex; switch (creditType) { case 0: cregx = /^3[47]\d{13}$/; break; case 1: cregx = /^30[0-5]\d{11}$|^3[68]\d{12}$/; break; case 2: cregx = /^6011\d{12}$/; break; case 3: cregx = /^5[1-5]\d{14}$/; break; case 4: cregx = /^4(\d{12}|\d{15})$/; break; } if (testPattern(wform.cnum, cregx) == false) isValid = false; return isValid; } function testPattern(field, reg) { var isValid = true; wsregx = /\s/g; var fv =field.value.replace(wsregx,""); if (reg.test(fv) == false) { isValid = false; document.getElementById(input.id+"fname").style.bgcolor="yellow"; } else { document.getElementById(input.id+"fname").style.bgcolor="white"; } return isValid; } function validCNum() { var isValid = true; wsregx = /\s/g; var fv = wform.cnum.value.replace(wsregx,""); if (luhn(fv)==false) { isValid = false; document.getElementById("cnum").style.bgcolor="yellow"; } else { document.getElementById("cnum").style.bgcolor="white"; } return isValid; } function changeColor(field) { var fv = field.value; if (fv.length==0) { field.style.background="yellow"; } else { field.style.background="white"; } } function validateForm() { var vLengths = validLengths(); var vPatterns = validPatterns(); var vCNum = validCNum(); var vForm = vLengths && vPatterns && vCNum; if (!vForm) { alert("Check the highlighted items in the form for missing/invalid data"); return false; } else { return true; } } Hello Every1 I need to edit the below form to use JavaScript to Validate if thr Title was put or Not .. its a template i use at my site to add comment and i want the Title to be Requier .Javascript seems the easiest way for me but dont know how. PHP Code: <{if $commentany.com_itemid}> <form action="comment_post.php" method="POST"> <input type="hidden" name="com_itemid" value="<{$commentany.com_itemid}>"> <input type="hidden" name="XOOPS_TOKEN_REQUEST" value="<{$commentany.xoops_token_request}>"> <table class='outer' cellspacing='1' style="margin-top:2em;"> <tr> <th colspan="2"><{$smarty.const._MB_COMMENTANY_LANG_NEW_COMMENT}></th> </tr> <{* <tr> <td class='head' align='left'><{$smarty.const._MB_COMMENTANY_LANG_RULE}></td> <td class='odd' align='left'> <{$commentany.rule_text}> </td> </tr> *}> <tr> <td class='head' align='left'><{$smarty.const._MB_COMMENTANY_LANG_ICON}></td> <td class='odd' align='left'> <{foreach item=i from=$commentany.com_icon}> <input type="radio" name="com_icon" value="<{$i}>"><img src="<{$smarty.const.XOOPS_URL}>/images/subject/<{$i}>"> <{/foreach}> </td> </tr> <tr> <td class='head' align='left'><{$smarty.const._MB_COMMENTANY_LANG_TITLE}></td> <td class='odd' align='left'> <input type="text" name="com_title" size="64" maxlength="255" value="<{$xoops_default_comment_title}>"> </td> </tr> <tr> <td class='head' align='left'><{$smarty.const._MB_COMMENTANY_LANG_TEXT}></td> <td class='odd' align='left'> <{xoopsdhtmltarea name="com_text" cols=50 rows=4}> </td> </tr> <{* <tr> <td class='head' align='left'><{$smarty.const._MB_COMMENTANY_LANG_OPTION}></td> <td class='odd' align='left'> <input type="checkbox" name="dosmiley" value="1" checked><{$smarty.const._CM_DOSMILEY}><br/> <input type="checkbox" name="doxcode" value="1" checked><{$smarty.const._CM_DOXCODE}><br/> <input type="checkbox" name="dobr" value="1" checked><{$smarty.const._CM_DOAUTOWRAP}><br/> </td> </tr> *}> <tr> <td class='head' align='left'></td> <td class='even' align='left'> <input type='submit' class='formButton' name='com_dopreview' id='com_dopreview' value='<{$smarty.const._MB_COMMENTANY_LANG_PREVIEW}>' /> <input type='submit' class='formButton' name='com_dopost' id='com_dopost' value='<{$smarty.const._MB_COMMENTANY_LANG_SUBMIT}>' /> </td> </tr> </table> <input type="hidden" name="dohtml" value="0" /> <input type="hidden" name="dosmiley" value="1" /> <input type="hidden" name="doxcode" value="1" /> <input type="hidden" name="dobr" value="1" /> </form> <{/if}> <{$commentsnav|replace:'button':'hidden'}> for some reason this is not working can anyone tell me why? Code: <script language="JavaScript" type="text/javascript"> function swap(nam,im) { eval("document." + nam + ".src=" + im + ".src"); } van_b = new Image; van_b.src = "images/bus_menu2/busmenub_Passvan01on.jpg"; van_a = new Image; van_a.src = "images/bus_menu2/busmenub_Passvan01off.jpg"; excoach_b = new Image; excoach_b.src = "images/bus_menu2/busmenuB_Excoach01on.jpg"; excoach_a = new Image; excoach_a.src = "images/bus_menu2/busmenuB_Excoach01off.jpg"; specialcoach_b = new Image; specialcoach_b.src = "images/bus_menu/busmenu_specialtycoach01on.jpg"; specialcoach_a = new Image; specialcoach_a.src = "images/bus_menu/busmenu_specialtycoach01off.jpg"; minicoach_b = new Image; minicoach_b.src = "images/bus_menu2/busmenuB_minicoach01on.jpg"; minicoach_a = new Image; minicoach_a.src = "images/bus_menu2/busmenuB_minicoach01off.jpg"; motorcoach_b = new Image; motorcoach_b.src = "images/bus_menu2/busmenub_motorcoach01on.jpg"; motorcoach_a = new Image; motorcoach_a.src = "images/bus_menu2/busmenub_motorcoach01off.jpg"; function checkForm() { frm = window.document.contactForm; if (frm.pickupmonth.value =='') { alert('Please enter valid pickup Month'); frm.pickupmonth.focus(); return false; } if(frm.pickupday.value== "") { alert('Please enter pickup Day'); frm.pickupday.focus(); return false; } if(frm.pickupyear.value == "") { alert('Please enter pickup Year'); frm.pickupyear.focus(); return false; } if(frm.pickupaddress.value == "") { alert('Please enter pickup Address'); frm.pickupaddress.focus(); return false; } if (frm.pickupcity.value== "") { alert('Please enter pickup City'); frm.pickupcity.focus(); return false; } if (!validateInt(frm.pickupzip.value)) { if(frm.pickupzip.value =="" ) alert('Please enter pickup Zip Code'); frm.pickupzip.value=""; frm.pickupzip.focus(); return false; } if(frm.pickuphour.value == "") { alert('Please enter pickup Hour'); frm.pickuphour.focus(); return false; } if(frm.pickupminute.value == "") { alert('Please enter pickup Minute'); frm.pickupminute.focus(); return false; } if(frm.pickupam.value == "") { alert('Please enter pickup AM or PM'); frm.pickupam.focus(); return false; } if(frm.dropoffaddress.value == "") { alert('Please enter dropoff Address'); frm.dropoffaddress.focus(); return false; } if(frm.dropoffcity.value == "") { alert('Please enter dropoff City'); frm.dropoffcity.focus(); return false; } if (!validateInt(frm.dropoffpzip.value)) { if(frm.dropoffpzip.value =="" ) alert('Please enter a valid dropoff Zip Code'); frm.dropoffpzip.value=""; frm.dropoffpzip.focus(); return false; } if(frm.arrivalhour.value == "") { alert('Please enter arrival Hour'); contactForm.arrivalhour.focus(); return false; } if(frm.arrivalmin.value == "") { alert('Please enter arrival Minute'); frm.arrivalmin.focus(); return false; } if(frm.arrivalam.value == "") { alert('Please enter arrival AM or PM'); frm.arrivalam.focus(); return false; } if(frm.vehicle.value == "") { alert('Please enter Vehicle Type'); frm.vehicle.focus(); return false; } if(frm.passengers.value == "") { alert('Please enter Amount of Passengers'); frm.passengers.focus(); return false; } if(frm.guestname.value == "") { alert('Please enter Name'); frm.guestname.focus(); return false; } if (!validateInt(frm.guestphone.value)) { if(frm.guestphone.value =="" ) alert('Please enter a valid Telephone number'); frm.guestphone.value=""; frm.cguestphone.focus(); return false; } if(!validateEmail(frm.guestemail.value) { alert('Please enter proper email address!'); frm.guestemail.focus(); return false; } function validateInt(val) { switch (isInteger(val)) { case true: return true; break; case false: alert("Please enter numbers only!"); return false; } } function isInteger (s) { var i; if (isEmpty(s)) if (isInteger.arguments.length == 1) return 0; else return (isInteger.arguments[1] == true); for (i = 0; i < s.length; i++) { var c = s.charAt(i); if (!isDigit(c)) return false; } return true; } function isEmpty(s) { return ((s == null) || (s.length == 0)) } function isDigit (c) { return ((c >= "0") && (c <= "9")) } function validateEmail(email){ // This function is used to validate a given e-mail // address for the proper syntax if (email == ""){ return false; } badStuff = ";:/,' \"\\"; for (i=0; i<badStuff.length; i++){ badCheck = badStuff.charAt(i) if (email.indexOf(badCheck,0) != -1){ return false; } } posOfAtSign = email.indexOf("@",1) if (posOfAtSign == -1){ return false; } if (email.indexOf("@",posOfAtSign+1) != -1){ return false; } posOfPeriod = email.indexOf(".", posOfAtSign) if (posOfPeriod == -1){ return false; } if (posOfPeriod+2 > email.length){ return false; } return true } </script> 1.I want to retain the value of the item selected from the drop down list even if the validation fails 2. The input element should be hghlighted red in colour which fails the validation <html> <script type="text/javascript"> <!-- function validate_form1 ( ) { valid = true; if ( document.contact_form1.question1.value=="" || document.contact_form1.question2.value == "" ) { alert ( "Select at least one option." ); //document.getElementById("question1").focus(); document.getElementById('contact_form1').question1.focus(); valid = false; } return valid; } function validate_form2 ( ) { valid = true; if ( document.contact_form2.question1.value=="" || document.contact_form2.question2.value == "" ) { alert ( "Select at least one option." ); //document.getElementById("question1").focus(); valid = false; } return valid; } //--> </script> <table border="5" width="300"> <tr> <td> <form name="contact_form1" action="DBsaving.php" method="post" onSubmit="return validate_form1 ( );"> 1. Question <select name="question1"><option selected="q1" value="">Select One...</option><option value="1">Yes</option><option value="2">No</option></select><br /><br /> 2. Question <select name="question2"><option selected="selected" value="">Select One...</option><option value="1">Yes</option><option value="2">No</option></select><br /><br /> 3. Faculty ID : <textarea name="comments" rows="2" cols="4"></textarea> <input type="submit" value="Submit" /> </form> </td> <td> <form name="contact_form2" action="DBsaving.php" method="post" onSubmit="return validate_form2 ( );" > 1. Question <select name="question1"><option selected="q1" value="">Select One...</option><option value="yes1">Yes</option><option value="no1">No</option></select><br /><br /> 2. Question <select name="question2"><option selected="selected" value="">Select One...</option><option value="yes">Yes</option><option value="no">No</option></select><br /><br /> 3. Faculty ID : <textarea name="comments" rows="2" cols="4"></textarea> <input type="submit" value="Submit" /> </form> </td> </tr> </table> </html> Hi guys, just need help so when there is no input into card number, postcode, what are you after, delivery address an error message comes up. Also I need to make it so when someone puts numbers in the first and last name or letters in the postcode it will come up error. I have done this for first and lastname but when I copy my code and try and put it on the others then no javascript works. thanks for your help Code: <html> <head> <script type="text/javascript"> function validate() { var at=document.getElementById("email").value.indexOf("@"); var age=document.getElementById("age").value; var fname=document.getElementById("fname").value; var lname=document.getElementById("lname").value; var ccn=document.getElementById("ccn").value; submitOK="true"; if (fname.length<1) { alert("Please Enter a Valid First Name"); submitOK="false"; } if (isNaN(age)||age<1||age>100) { alert("Age Must be between 1 and 100"); submitOK="false"; } if (lname.length<1) { alert("Please Enter a Last Name"); submitOK="false"; } if (isNaN(age)||age<1||age>100) { alert("Age Must be between 1 and 100"); submitOK="false"; } if (at==-1) { alert("Not a Valid Email Address"); submitOK="false"; } if (submitOK=="false") { return false; if (ccn.length>16) { alert("Credit Card Number is False"); submitOK="false"; } } } </script> </head> <body> <form action="tryjs_submitpage.htm" onsubmit="return validate()"> Name : <input type="text" id="fname" size="20"><br /> Last Name : <input type="text" id="lname" size="20"><br /> Age: <input type="text" size="2" id="age" maxlength="2"> Email: <input type="text" id="email" size="20"><br /> <table><tr> <td><p>Type of Card</p></td> <td><form action="21"> <select name="cars"> <option value="season"> </option> <option value="season">Mastercard</option> <option value="season">Diners Club</option> <option value="season">Visa</option> </select></form></td></tr> </table> <table><tr> <td><p>Expiry Date</p></td> <td><form action="21"> <select name="cars"> <option value="season"> </option> <option value="season">2010</option> <option value="season">2011</option> <option value="season">2012</option> </select></form></td></tr> </table> Card Number : <input type="text" id="ccn" size="20"><br /> Postcode: <input type="text" size="2" id="postcode" maxlength="4"> Delivery Address: <input type="text" id="da" size="20"><br /> Suburb: <input type="text" id="suburb" size="10"><br /> <table><tr> <td><p>What are you after</p></td> <td><form action="21"> <select name="cars"> <option value="poker products"> </option> <option value="poker chips">Poker Table</option> <option value="poker table">Poker Chips</option> <option value="poker table">Both</option> </select></form></td></tr> </table> <input type="submit" value="Submit"> </form> </body> </html> Hi, validation for pin must not be allow given below conditions 6 rising consecutive numbers(e.g 123456,456789 etc) 6 Descending consecutive numbers (eg. 654321,987654) All same digit (eg 111111,222222) Same digit appearing 3 or more time in pin code (eg:121212,1111432) I am new to this forum.. and I am hoping to get help with this javascript validation for my form for my assignment. trying to validate multiple fields. I have never done javascript, so with my limited understanding from Google, I put together code snippets. Problems: 1. How can I get one message box when the user presses submit indicating all failed validation at one time 2. The expired credit card validation doesnt work 3. Cant seem to find a good "confirm password" script 3. The form does not submit if all the fields are correct. <script language="javascript"> <!-- function checkAge() { var bday=parseInt(document.forms[0].txtBday.value); var bmo=(parseInt(document.forms[0].txtBmo.value)-1); var byr=parseInt(document.forms[0].txtByr.value); var byr; var age; var now = new Date(); tday=now.getDate(); tmo=(now.getMonth()); tyr=(now.getFullYear()); { if((tmo > bmo)||(tmo==bmo & tday>=bday)) { age=(tyr-byr) } else { age=(tyr-(byr+1)) } if (age<18) { alert ("you must be over 18 years"); return false; } else { return true; } } } //--> function checkEmail() { var x=document.getElementById("email").value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } { return true; } } function onlyNumbers(evt) { var e = event || evt; // for trans-browser compatibility var charCode = e.which || e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; { return true; } } function checkCardNumber() { var x = document.getElementById("cardNumber").value; if (x.length<16) { alert("Your Credit Card Number must be 16 digits"); return false; } { return true; } } function checkSecurityCode() { var y = document.getElementById("securityCode").value; if (y.length<3) { alert("Your Security number must be three digits"); return false; } { return true; } } function ValidateExpDate() { var ccExpYear = 20 + $F('<%= expYear.ClientID%>'); var ccExpMonth = $F('<%= expMonth.ClientID%>'); var expDate=new Date(); expDate.setFullYear(ccExpYear, ccExpMonth, 1); var today = new Date(); if (expDate<today) { alert("card expired"); // Credit Card is expire return false; } else { // Credit is valid return true; } } function runall() { checkAge(); checkEmail(); checkCardNumber(); checkSecurityCode(); { return false;} } </script> Hi. I am trying to do some sim[ple form validation using javascript. I have a simple html file 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>Send Card</title> <script language="JavaScript" src="gen_validatorv31.js" type="text/javascript"></script> </head> <body> <form action="getName.php" onsubmit="return validate_form(this);"> Receiver (To): <input type="text" name="name"><br> Sender (From): <input type="text" name="sender"><br> Email: <input type="text" name="email"><br> <input type="submit" value="Submit"> </form> </body> </html> Which calls up my javascript and php file (The php file should only be used when the javascript has found no errors). Now I have a js file which does some validation Code: <script type="text/javascript"> function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt); return false; } else { return true; } } } function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@") dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) { alert(alerttxt); return false; } else { return true; } } } function validate_form(thisform) { with (thisform) { if (validate_required(name,"Please specify your name!")==false) { name.focus(); return false; } if (validate_required(sender,"Please specify the receivers name!")==false) { sender.focus(); return false; } if (validate_required(email,"Email must be filled out!")==false) { email.focus(); return false; } if (validate_email(email,"Not a valid e-mail address!")==false) { email.focus(); return false; } } } </script> When I run it on my server, I get the form and enter nothing into it, I just click submit. However, it goes straight to the php file and brings up my flash movie, which it shouldnt do. When nothing is entered, the js file should return the error. I thought I had everything set up correctly, but obviously not. Can someone see where I am going wrong? cheers I am using Javascript validation, for all my HTML control that are not run at server... Now i need to allow the user to enter only numbers in a textbox..If any of them apply characters alert should come.. How can i do that in javascript.... Anyone know how do I use javascript to limit the numeric amount enetered in a text box less than 1000?
function StrongPassword(Input) { //var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; //1 number,1 Uppercase,1 lowercase,6 characters var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/; //1 digit,1 Uppercase,1 lowercase if (re.test(Input)) { alert('Strong Password'); } else { alert('Weak pwd'); } } Help to get correct output.... both the expr will execute the else block only... This are my codes.. var add = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var email = form.txtEmail.value; if (add.test(email) = false) { alert("Please enter a valid email."); return false; } return true; } bt it wun work.. pls help.. Hello I need some help with validating the password strength of my form. I am actually looking for a regular expression that could force the users to have at least 2 of the following: 1. Upper and lower case. 2. Numbers 3. Symbols. Thanks in advance for any help Hello Everyone. And thank you for your help in advance. The code below is a basic HTML form that utilizes some javascript validation and CSS styling. It checks to see if the textbox field Is EMPTY. If it is an alert box appears displaying a message that the e-mail field is BLANK. In addition, the empty text box field is outlined in RED. That is great but I ALSO require it to perform some e-mail validation (i.e.) if an incorrect e-mail address is entered an alert box is displayed notifying the user of the error and outlining the text-box yet again. Any and ALL help would be nice. "Thank you." <html> <head> <title>Validation</title> <style type="text/css"> .inpBox { background-color: #FFFFFF; border: solid 2px #666666; } .inpBoxError { border: solid 4px #FF0000; } </style> <script type="text/javascript"> function verify_login(form_id,email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var login_email = document.getElementById("email"); var msg = ""; if (login_email.value == "") { msg+= "Email address field cannot be left BLANK \n"; login_email.className = "inpBoxError"; } if (msg == "") { return true; } else { alert(msg); return false; } } </script> </head> <hody> <form id="form_id" method="POST" action="" onSubmit="return verify_login(form_id,email);"> <table border="1" width="30%"> <tr> <td width="15%"><div align="right"><b>E-Mail:</b></td> <td width="15%"><div align="left"><input id="email" name="email" type="text"></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"><div align="center"><input id="submit" name="submit" type="submit" value="Register"></div></td> </tr> <table> </form> </hody> </html> 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 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. Hi, I have a form on my website and I want to validate the phone field. I found a good script to do it but I need to combine the script with the other validation that I have on my form. Can you help me add this phone validation script into the other validations that I have so that it is just one javascript? Here is the phone validation script: <script language = "Javascript"> /** * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/) */ // Declaring required variables var digits = "0123456789"; // non-digit characters which are allowed in phone numbers var phoneNumberDelimiters = "()- "; // characters which are allowed in international phone numbers // (a leading + is OK) var validWorldPhoneChars = phoneNumberDelimiters + "+"; // Minimum no of digits in an international phone no. var minDigitsInIPhoneNumber = 10; function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function trim(s) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not a whitespace, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (c != " ") returnString += c; } return returnString; } function stripCharsInBag(s, bag) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function checkInternationalPhone(strPhone){ var bracket=3 strPhone=trim(strPhone) if(strPhone.indexOf("+")>1) return false if(strPhone.indexOf("-")!=-1)bracket=bracket+1 if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false var brchr=strPhone.indexOf("(") if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false s=stripCharsInBag(strPhone,validWorldPhoneChars); return (isInteger(s) && s.length >= minDigitsInIPhoneNumber); } function ValidateForm(){ var Phone=document.frmSample.txtPhone if ((Phone.value==null)||(Phone.value=="")){ alert("Please Enter your Phone Number") Phone.focus() return false } if (checkInternationalPhone(Phone.value)==false){ alert("Please Enter a Valid Phone Number") Phone.value="" Phone.focus() return false } return true } </script> Here are the validations for the other fields: <script type="text/JavaScript"> function validate_form(){ err = 'The following fields are not correct filled:\n'; if (document.form1.name.value == ''){ err += 'No First Name.\n'; } if (document.form1.from.value == ''){ err += 'No Email Address.\n'; } if (document.form1.elements['custom State'].value == ''){ err += 'No State.\n'; } if (document.form1.elements['custom Phone'].value == ''){ err += 'No Phone.\n'; } if (emailCheck(document.form1.from.value) == false){ err += 'No Valid email.\n'; } if (document.form1.terms.checked != true){ err += 'You did not agree with the terms.\n'; } if (err != 'The following fields are not correct filled:\n'){ alert (err); return false; } else{ return true; } } var str_vars = ''; function all_fields(){ str_vars = ''; el = document.form1; for (var i = 0; i < el.elements.length; i++) { if (el.elements[i].value != '') str_vars += el.elements[i].name+'='+el.elements[i].value+'&'; } str_vars = str_vars.substr(0,str_vars.length-15);; } </script> Thank you, Leroy Hey guys, im a bit of a loser with Javascript and need a bit of validation done but I have no idea what the problem is with my code, can anyone help? Form: Code: <div id="Layer3"> <form id="form" name="form" method="post" onsubmit='return formValidator(form)' action="Candidate output.php"> <p class="style3"><u>Search for a Candidate </u></p> <p class="style3">Candidate ID <input type="text" name="CandidateID" /> </p> <p class="style3">File <select name="File"> <option>--Select--</option> <option>To be deleted</option> </p> <p class="style3">Name <input type="text" name="Name" /> </p> <p class="style3">Current Job Title <select name="Current_Job_title"> <option>--Select--</option> <option>Accessories</option> </select> </p> <p class="style3">Contact Telephone <input type="text" name="Contact_Telephone" /> </p> <p class="style3">Contact Email <input type="text" name="Contact_Email" /> </p> <p class="style3">Town <input type="text" name="Town" /> </p> <p class="style3">County <select name="County"> <option>--Select--</option> <option>Aberdeenshire</option> </select> </p> <p class="style3">Postcode <input type="text" name="Postcode" /> </p> <p class="style3">Languages spoken <input type="text" name="Languages_Spoken" /> </p> <p class="style3">Previous Job Title <select name="Job_Title" > <option>--Select--</option> <option>Accessories</option> </select> </p> <p class="style3">Previous Employer <input type="text" name="Employer" /> </p> <p class="style3">Previous Employment Type <select name="Employment_Type"> <option>--Select--</option> <option>Manufacturer</option> </select> </p> <p class="style3">Previous Department Type <select name="Department_type"> <option>--Select--</option> <option>Accounts</option> </select> </p> <p class="style3">Order By <select name="Order_By"> <option>--Select--</option> <option>CandidateID</option> </select> <input type="checkbox" name="Desc" value="y" /> Decending (Ascending leave unchecked) </p> <p class="style3"> <input type="submit" name="Submit" value="Submit" /> </p> </form> </div> Validation in the <Head>; <script language="JavaScript" type='text/javascript'> function formValidator(form){ // Make quick references to our fields var CandidateID = document.getElementById('CandidateID'); var Name = document.getElementById('Name'); var Contact_T = document.getElementById('Contact_Telephone'); var Contact_E = document.getElementById('Contact_Email'); var Town = document.getElementById('Town'); var Postcode = document.getElementById('Postcode'); var Ls = document.getElementById('Languages_Spoken'); var P_Employer = document.getElementById('Previous_Employer'); /*http://www.tizag.com/javascriptT/javascriptform.php*/ // Check each input in the order that it appears in the form! if(isNumeric(CandiateID, "Please enter numbers only")){ if(isAlphabet(Name, "Please enter letters only")){ if(isNumeric(Contact_T, "Please enter numbers only")){ if(lengthrestriction(Contact_T, 11)){ if(emailValidator(Contact_E, "Please enter a valid email address")){ if(isAlphabet(Town, "Please enter letters only")){ if(postit(Postcode, "Please enter a valid Postcode")){ if(isAlphabet(LS, "Please enter letters only")){ if(isAlphabet(P_Employer, "Please enter letters only")){ return true; } } } } } } } } } return false; function isNumeric(elem, alerttxt){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(alerttxt); elem.focus(); return false; } } function isAlphabet(elem, alerttxt){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(alerttxt); elem.focus(); return false; } } function isAlphanumeric(elem, alerttxt){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(alerttxt); elem.focus(); return false; } } function lengthRestriction(elem, max){ var uInput = elem.value; if(uInput.length >= uInput.length <= max){ return true; }else{ alert("Please enter between 0 and " +max+ " characters"); elem.focus(); return false; } } function emailValidator(elem, alerttxt){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(alerttxt); elem.focus(); return false; } } function postit(elem, alerttxt){ //check postcode format is valid test = document.details.Postcode.value; size = test.length test = test.toUpperCase(); //Change to uppercase while (test.slice(0,1) == " ") //Strip leading spaces {test = test.substr(1,size-1);size = test.length } while(test.slice(size-1,size)== " ") //Strip trailing spaces {test = test.substr(0,size-1);size = test.length } document.details.Postcode.value = test; //write back to form field if (size < 6 || size > 8){ //Code length rule alert(test + " is not a valid postcode - wrong length"); document.details.Postcode.focus(); return false; } if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule alert(test + " is not a valid postcode - cannot start with a number"); document.details.Postcode.focus(); return false; } if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule alert(test + " is not a valid postcode - alpha character in wrong position"); document.details.Postcode.focus(); return false; } if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule alert(test + " is not a valid postcode - number in wrong position"); document.details.Postcode.focus(); return false; } if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule alert(test + " is not a valid postcode - number in wrong position"); document.details.Postcode.focus(); return false; } if (!(test.charAt(size-4) == " ")){//space in position length-3 rule alert(test + " is not a valid postcode - no space or space in wrong position"); document.details.Postcode.focus(); return false; } count1 = test.indexOf(" ");count2 = test.lastIndexOf(" "); if (count1 != count2){//only one space rule alert(test + " is not a valid postcode - only one space allowed"); document.details.Postcode.focus(); return false; } alert("Postcode Format OK"); return true; } </script> Im sure there are a few syntax errors but any and all help is greatly appreciated 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. Hi Folks, I'm new here, as well as to JavaScript, and am stuck. I'm trying to get something to validate using the W3C file validation, and I'm stuck. This is XHTML 1.0 Strick, and I know that isn't JS, but since the error involved JS I posted it here. If I would be better putting it in HTML please let me know. Everything works fine on the page, but I keep getting one single error. The > in Red is what shows up as the issue. Do ya'll see something glaringly obvious that I did wrong? Thanks for the help! Code: document.write("<a href='mailto:" + emLink + "' > "); |