JavaScript - Password Validator
Hello!
I'm doing an assignment that validates a password field, the password field should only contain numbers, however this code only verifies the first number input in the field, which means i need to check through every singel input in the field, so i got a little problem <script> function checkPassword(strng) { var text = strng.value; var regel = text.replace(/[\(\)\.\-\ ]/g, ''); if(isNaN(parseInt(text))) { window.alert("Fel, password is not a number:" + text); } } else { window.alert("correct e-mail and password!"); } } </script> I've been thinking about a for loop should fix the problem, but im new to javascript, some help would be appreciated! Similar TutorialsI'm having trouble getting two password boxes to work on the same page, which I created using the JavaScript Kit Encrypted Password Generator (http://www.javascriptkit.com/epassword/index.htm). I've used the code that this generator produces, with some modifications as given by cheesebagpipe (http://www.codingforums.com/showthread.php?t=14646). These changes enable the user to press the keyboard's enter key to submit the password (as an alternative to clicking the submit button), and will also refocus the text box and select the text in it if the user enters the wrong password. The code works fine on pages with just one box (e.g. http://www.mistymusic.co.uk/StLuke's.html), but what changes are needed to make two work on the same page? (I'm new to web design and clueless when it comes to JavaScript, which I know isn't the most secure method of password protection, but will do for now). At the moment, on pages with two boxes (e.g. http://www.mistymusic.co.uk/BEAP.html), neither of the boxes work; this appears in the address bar instead: 'http://www.mistymusic.co.uk/BEAP.html?password2=help!' ('help!'=whatever has been entered in the text box). The full code for both boxes is given below. Code: <div id="passwordBoxes"> <div id="password2"> <form name="password1" onsubmit="submitentry();return false;"> <span class="WhiteLogin">Keyboard classes login</span> <input name="password2" type="password" class="AlignedFormBoxes" size="15" /> <input type="button" class="AlignedFormBoxes" value="Login" /> </form> </div> <div id="password1"> <form name="password1" onsubmit="submitentry();return false;"> <span class="WhiteLogin">Community Youth Choir login</span> <input name="password2" type="password" class="AlignedFormBoxes" size="15" /> <input type="button" class="AlignedFormBoxes" value="Login" /> </form> </div> </div> <script> var pass=new Array() var t3="" var lim=6 pass[0]="gc3Gu5uygvU8VDA" pass[1]="aNL6yjrU5AAKyy3" pass[2]="enSaX8glavp54H" pass[3]="WF3XUKEpbbMEx" pass[4]="8Pv7bsEqaIjNdb6b" pass[5]="35Pv7bsEqaIjNdb6" //configure extension to reflect the extension type of the target web page (ie: .htm or .html) var extension=".html" var enablelocking=0 var numletter="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var temp3='' var cur=0 function max(which){ return (pass[Math.ceil(which)+(3&15)].substring(0,1)) } function testit(input){ temp=numletter.indexOf(input) var temp2=temp^parseInt(pass[phase1-1+(1|3)].substring(0,2)) temp2=numletter.substring(temp2,temp2+1) return (temp2) } function submitentry(){ t3='' verification=document.password1.password2.value phase1=Math.ceil(Math.random())-6+(2<<2) var indicate=true for (i=(1&2);i<window.max(Math.LOG10E);i++) t3+=testit(verification.charAt(i)) for (i=(1&2);i<lim;i++){ if (t3.charAt(i)!=pass[phase1+Math.round(Math.sin(Math.PI/2)-1)].charAt(i)) indicate=false } if (verification.length!=window.max(Math.LOG10E)) indicate=false if (indicate) window.location=verification+extension; else { alert("That wasn't the correct password. Please check that your CAPS Lock key is turned off and try again."); document.password1.password2.focus(); document.password1.password2.select(); } } </script> <script> var pass=new Array() var t3="" var lim=7 pass[0]="Qmsn8tUQZX4T0PC" pass[1]="DUtntGtFhaTppWO" pass[2]="JahI7L4JqbxZrwS" pass[3]="ong1qqnbr9rvV2s" pass[4]="7BlqC2sc8hQ8bWMK" pass[5]="15BlqC2sc8hQ8bWM" //configure extension to reflect the extension type of the target web page (ie: .htm or .html) var extension=".html" var enablelocking=0 var numletter="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var temp3='' var cur=0 function max(which){ return (pass[Math.ceil(which)+(3&15)].substring(0,1)) } function testit(input){ temp=numletter.indexOf(input) var temp2=temp^parseInt(pass[phase1-1+(1|3)].substring(0,2)) temp2=numletter.substring(temp2,temp2+1) return (temp2) } function submitentry(){ t3='' verification=document.password1.password2.value phase1=Math.ceil(Math.random())-6+(2<<2) var indicate=true for (i=(1&2);i<window.max(Math.LOG10E);i++) t3+=testit(verification.charAt(i)) for (i=(1&2);i<lim;i++){ if (t3.charAt(i)!=pass[phase1+Math.round(Math.sin(Math.PI/2)-1)].charAt(i)) indicate=false } if (verification.length!=window.max(Math.LOG10E)) indicate=false if (indicate) window.location=verification+extension; else { alert("That wasn't the correct password. Please check that your CAPS Lock key is turned off and try again."); document.password1.password2.focus(); document.password1.password2.select(); } } </script> Any help would be a lifesaver - thanks in advance! Hello! I have started using php/html/javascript just recently so I'm not too familiar with it yet, however I think I've done alright. I have apache installed so I can mess around with my files and perfect stuff, so I've created a form that a user fills out, pushes a button, and it prints the information in an organized fashion. It works perfectly for the most part, and I have a validator script that ensures all of the fields work correctly. All of that works great, however I recently uploaded all of the files to a hosted server and the validator stopped picking up for some reason. Anyone have any idea why on localhost a form validator script would work but hosted it wouldn't? Any insight would be great. I've added the two scripts below: Form (php) code:http://pastebin.com/J83AX6GG Validator (JS) code: http://pastebin.com/LMuLu3Jp Thank you for your time! Hello, I don't see what the problem is with my form validation script. It does not validate. Please point it out to me. Code: <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["name"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Please enter a valid email address"); return false; } var x=document.forms["myForm"]["message"].value; if (x==null || x=="") { alert("You have not entered a message"); return false; } } </script> html Code: <form name="myForm" action="contact.php" onsubmit="return validateForm()" method="post"> First name: </p> <input type="text" name="name"> </p> Email address: </p> <input type="text" name="email"> </p> Subject: </p> <input type="text" name="subject"> </p> Message: </p> <textarea name="message" rows="15" cols="50"></textarea> </p> <input type="submit" value="Submit"> </form> the script is in the <head> section and html in the <body>. Thank you. How would you make a password feild and a retype password feild and they have to be the same?
<script type="text/javascript"> Code: function switch1(div) { if (document.getElementById('one')) { var option=['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']; for(var i=0; i<option.length; i++) { obj=document.getElementById(option[i]); obj.style.display=(option[i]==div)? "block" : "none"; }}}// function switchImg(i){document.images["wine"].src = i;} </script> used in this page seems to object to option.length Frank. HTML: Code: <script src="./include/js/drinkValidation.js" type="text/javascript"></script> <form name="add-drinks" action="include/add-drink.php" method="POST" onSubmit="return addDrinkFormValidation(this);" enctype="multipart/form-data" > <span id="colour" class='modify_form'> <label for='drinkColour'>Spirit Colour:</label> <br /> <select name='drinkColour' tabindex=1> <option value='' >None</option> <option value='R' >R</option> <option value='G' >G</option> <option value='Y' >Y</option> </select> </span> <div class='modify_form'> <label for='drinkType'>Type:</label> <br /> <select name='drinkType' tabindex=1 onChange="HideObjects(this.value)"> <option value="">Select a Drink type:</option> <option value='Cask' >Cask Ales</option> <option value='Guest' >Guest Ale</option> <option value='Lager' >Lager</option> <option value='Bottled Beers' >Bottled Beer</option> <option value='Wines' >Wine</option> <option value='Ciders' >Cider</option> <option value='Softs' >Soft</option> <option value='Spirits' >Spirit</option> </select> </div> <div id="drinkABV" class='modify_form'> <label for='drinkABV'>ABV:</label> <br /> <input name='drinkABV' size='2' tabindex=4 maxlength="4" placeholder="ie: 4.2"/> <label for='drinkABV'>%</label> </div> <div id="name"class='modify_form'> <label for='name'>Name:</label> <br /> <input name='name' size='25' tabindex=3 placeholder="Drink name"/> </div> <div id="drinkInfo" class='modify_form'> <label for='drinkInfo'>Description:</label> <br /> <textarea name='drinkInfo' rows='5' cols='30' maxlength='255' tabindex=5 placeholder="Max 255 characters"></textarea> </div> <div id="pint" class='modify_form'> <label for='drinkPintPrice'>Pint (£):</label> <br /> <input name='drinkPintPrice' size='10' tabindex=8 /> </div> <div id="halfpint" class='modify_form'> <label for='drinkHalfPrice'>Half Pint (£):</label> <br /> <input name='drinkHalfPrice' size='10' tabindex=7 /> </div> <div id="drinkSpecialPrice" class='modify_form'> <label for='drinkSpecialPrice'>Offer Price (£):</label> <br /> <input name='drinkSpecialPrice' size='10'tabindex=6 /> </div> <div id="drinkbottlePrice" class='modify_form'> <label for='drinkbottlePrice'>Bottle/Spirit Price (£):</label> <br /> <input name='drinkbottlePrice' size='10'tabindex=6 /> </div> <br /> <br /> <input type="file" name="cons_image" /> <br /> <br /> <div id='submit'> <input type='submit' value='Add New Drink' /> </div> <br /> <p><b>Please add the information you wish to add then click Add New Drink</b></p> </form> Javascript containing validation Code: var ck_abv = /[0-9]{1,2}\\.[0-9]{1}$/; var ck_price = /[0-9]{1,2}\\.[0-9]{2}$/; var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_info = /^[A-Za-z0-9 ]{3,255}$/; alert ("Im in the file"); function addDrinkFormValidation(form){ var type = form.drinkType.value; var abv = form.drinkABV.value; var name = form.name.value; var info = form.drinkInfo.value; var pint = form.pint.value; var halfpint = form.halfpint.value; var bottle = form.drinkbottleprice.value; var offer = form.drinkSpecialprice.value; var errors = []; alert (form); alert (type); alert (abv); alert (info); alert (pint); alert (halfpint); alert ("Anything showing"); if(type==0){ errors[errors.length] = "Please select a drink type."; } if(!ck_name.test(name) || (name == "")){ errors[errors.length] = "Please enter a drink name."; } if(!ck_info.test(info) || (info == "")){ errors[errors.length] = "Please enter a drink description."; } if(!ck_abv.test(abv)){ errors[errors.length] = "Illegal character in ABV"; } if(!ck_price.test(pint)){ errors[errors.length] = "Illegal character in pint"; } if(!ck_price.test(halfpint)){ errors[errors.length] = "Illegal character in halfpint"; } if(!ck_price.test(bottle)){ errors[errors.length] = "Illegal character in Bottle/Spirit Price"; } if(!ck_price.test(offer)){ errors[errors.length] = "Illegal character in Offer price"; } if (errors.length > 0) { reportErrors(errors); return false; } return false; } function reportErrors(errors){ var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } For some reason i dont know why the javascript isnt reading the function even tho they are correctly named, the file is being read as the 1st test alert comes up. the 2nd one inside the function doesnt know. can anyone point in the right place or show me where i am going wrong. as you can see i have put both my entire form and and the java file up. so you can easily see what goes on #on a note i have multiple forms in a tab system if that has anything to do with it although i shouldnt see why it should. #oh and did i get my regex correct for ck_price e.g "9.99 or 10.99" and ck_abv eg "4.2 or 10.2 or 34" #im also using wampserver 2.1 with win7 and chrome if it's needed thanks ste Hi There, I really need your help. I am aware that there is no isDate() function for javascript, however, how could one check a date against a validator to ensure that the date entered is either returned true or false the date format that I would like to check would consist of the dd/mm/yyyy so essentially: isDate("12/01/2012") would return as true isDate("N/A") = would return as false I have searched high and low and am counting on the experts on this forum for some major help. A huge thanks in advance and I really appreciate everything. Cheers, Jay I have the following script in the head; Code: <script type="text/javascript"> <![CDATA[ <!--This function validates the data from the three input boxes on the MAILTO form--> function validate() { Check="Valid"; Name=document.contact.name.value; Mail=document.contact.mail.value; Comment=document.contact.comment.value; if (Name=="your name" || Name.length<1) { alert("Please enter your name"); Check="Invalid"; } else if (Mail.indexOf("@")<1 || Mail.indexOf(".")<1) { alert("Please enter a valid email address"); Check="Invalid"; } else if (Comment=="your comment" || Comment.length<1) { alert("Please enter your comment"); Check="Invalid"; } if (Check=="Invalid") { return false; } else { alert("Thank you for your comment"); } } ]]> </script> and the following form in the body; Code: <div> <form name="contact" onsubmit="return validate()" action="email.asp" method="post"> <div class="input_title">Name:</div><input type="text" name="name" size="25" class="input_box" /> <br /> <div class="input_title">Your Email:</div><input type="text" name="sender" size="25" class="input_box" /> <br /> <div class="input_title">Phone Number:</div><input type="text" name="tel" size="25" class="input_box" />(Optional) <br /> Message: <br /> <textarea name="enquiry" cols="50" rows="6" class="input_box"></textarea> <br /> <input type="submit" value="Submit" name="submit" /><input type="reset" value="Reset" name="reset" /> <br /> </form> <br /><br /> </div> It is a aspx file and validates fine as XHTML Trans. Why won't it work? Hello all. I am trying to track down why this custom validator is failing with an error that args is undefined. There are two funnctions - one works and one does not. Here they a the bold italicized item is where the error is being generated. Function validHygieneNote works as expected however. Code: function validClothingNote(val,args) { var radio_choice = false; var chks = document.getElementById('clothingNote'); var chks2 = document.getElementsByName('clothingInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} function validHygieneNote(val,args) { var radio_choice = false; var chks = document.getElementById('hygieneNote'); var chks2 = document.getElementsByName('hygieneInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} Because of my rather second-rate vision; I would like to get an editor for my Javascript that will check my syntax for me. Missing or extra brackets, semicolons etc are the bane of my life. Any suggestions welcomed. Frank Hello, I am trying to add a simple script to my CSS menu for a little bit more eye candy. However, when I add the script - it causes issues in my online store (ex; the javascript-powered one page checkout stops working). Here is the exact error from the error console: Quote: Error: jQuery.validator is undefined Source File: https://www.gem-tech.com/store/pc/onepagecheckout.asp Line: 288 And here is the exact script: Quote: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript" src="jquery.hoverIntent.minified.js"></script> <script type="text/javascript"> $(document).ready(function() { function megaHoverOver(){ $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Calculate width of all ul's (function($) { jQuery.fn.calcSubWidth = function() { rowWidth = 0; //Calculate row $(this).find("ul").each(function() { rowWidth += $(this).width(); }); }; })(jQuery); if ( $(this).find(".row").length > 0 ) { //If row exists... var biggestRow = 0; //Calculate each row $(this).find(".row").each(function() { $(this).calcSubWidth(); //Find biggest row if(rowWidth > biggestRow) { biggestRow = rowWidth; } }); //Set width $(this).find(".sub").css({'width' :biggestRow}); $(this).find(".row:last").css({'margin':'0'}); } else { //If row does not exist... $(this).calcSubWidth(); //Set Width $(this).find(".sub").css({'width' : rowWidth}); } } function megaHoverOut(){ $(this).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); }); } var config = { sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) interval: 100, // number = milliseconds for onMouseOver polling interval over: megaHoverOver, // function = onMouseOver callback (REQUIRED) timeout: 500, // number = milliseconds delay before onMouseOut out: megaHoverOut // function = onMouseOut callback (REQUIRED) }; $("ul#topnav li .sub").css({'opacity':'0'}); $("ul#topnav li").hoverIntent(config); }); </script> I believe there is some sort of conflict? Not sure though. Any input on this? Thanks, Hi, basically it's a simple postcode validator. It checks to see whether the postcode is in UK format, then tells you if it isn't with an alert box, then I want it to clear the field. The input field's ID is postcode. Code: function testPostCode () { var myPostCode = document.getElementById('postcode').value; if (checkPostCode (myPostCode)) { document.getElementById('postcode').value = checkPostCode (myPostCode) } else {alert ("Please enter your Postcode correctly, this includes:\n \n * Correct Spacing - AA1 1AA \n * Correct amount of letters and numbers. \n \n Sorry if this causes any inconvenience, but it is to your benefit.")}; document.postcode.value=""; } Anyone able to help me? Hi, I've been looking for a client-side form validation script which will check each field before submitting the form. Can anyone point me to a good one that looks professional. I want it to make a nice presentation of any errors as well, perhaps, as showing a 'tick' sign when the field is correctly filled in . bazz Validator (My CSE HTML Validator v9.0 ) reports javascript errors but program runs. There seems to be a problem with commands used twice and a missing semi-colon. Also there are problems with Firefox. Unable to reselect another image. OK with IE8. I would appreciate it if someone with better eyesight than me could give the jscript a once over for me. Thanks oin advance. Frank Culprit is here. EDITED. I know this is not very secure, but there is a problem with this and I am not sure how to go on. Code: <form> <input type="text" name="password"/> <input type="button" onclick="check()"/> </form> What is wrong with my javascript? Code: function check (){ if(password=="pass1"){ alert('Password is correct!') } } I am struggling trying to get this bit of code I've written to work. It should validate a password that is 10 characters long, starts with a D and includes 1 *. Even if I blank out two of the while statements and only use the charAt while statement it still fails to loop back. Any ideas? function validatePassword() { //declare and initialise variables var intCount = 0; var intCharCount = 7; var intAstrixCount =0; var strPassword = parseInt(prompt("Please enter password", "")); while (strPassword.length < intCount) { alert ("Your password must be at least 10 characters long"); strPassword = parseInt(prompt("Please enter password", "")); intCount++; } while (strPassword.charAt(0) != "a") { alert ("Your password does not start with a D"); strPassword = parseInt(prompt("Please enter password", "")); intCount++; } while (intAstrixCount != 1) { alert ("Your password does not contain an *"); strPassword = parseInt(prompt("Please enter password", "")); intCount++; } alert ("Your password is correct"); } I have a password check on my join form but it looks ugly the idea is good but it is all unaligned and makes the form look bad. I was wondering if you guys can help me format it i tried my self but it just caused it to not work at all lol. Right now it looks like this: ---------------------------- | -------- bar color -------- | ---------------------------- GOOD PASSWORD What i want is it to appear like this: __________________________ | -------- Good Pass -------- | <- Color in the bg,words in the box! Code: (function(A){A.extend(A.fn,{pstrength:function(B){var B=A.extend({verdects:["Very weak","Weak","Medium","Strong","Very strong"],colors:["#f00","#c06","#f60","#3c0","#3f0"],scores:[10,15,30,40],common:["password","sex","god","123456","123","cute","gamer","qwerty","monkey", "apple"],minchar:6},B);return this.each(function(){var C=A(this).attr("id");A(this).after("");A(this).after("<div class=\"pstrength-info\" id=\""+C+"_text\"></div>");A(this).after("<div class=\"pstrength-bar\" id=\""+C+"_bar\" style=\"margin-top: 5px; border: 1px solid gray; font-size: 1px; height: 15px; width: 260px;\"></div>");A(this).keyup(function(){A.fn.runPassword(A(this).val(),C,B)})})},runPassword:function(D,F,C){nPerc=A.fn.checkPassword(D,C);var B="#"+F+"_bar";var E="#"+F+"_text";if(nPerc==-200){strColor="#000";strText="Unsafe password word!";A(B).css({width:"0%"})}else{if(nPerc<0&&nPerc>-199){strColor="#ccc";strText="Too short";A(B).css({width:"5%"})}else{if(nPerc<=C.scores[0]){strColor=C.colors[0];strText=C.verdects[0];A(B).css({width:"10%"})}else{if(nPerc>C.scores[0]&&nPerc<=C.scores[1]){strColor=C.colors[1];strText=C.verdects[1];A(B).css({width:"25%"})}else{if(nPerc>C.scores[1]&&nPerc<=C.scores[2]){strColor=C.colors[2];strText=C.verdects[2];A(B).css({width:"50%"})}else{if(nPerc>C.scores[2]&&nPerc<=C.scores[3]){strColor=C.colors[3];strText=C.verdects[3];A(B).css({width:"75%"})}else{strColor=C.colors[4];strText=C.verdects[4];A(B).css({width:"92%"})}}}}}}A(B).css({backgroundColor:strColor});A(E).html("<span style='color: "+strColor+";'>"+strText+"</span>")},checkPassword:function(C,B){var F=0;var E=B.verdects[0];if(C.length<B.minchar){F=(F-100)}else{if(C.length>=B.minchar&&C.length<=(B.minchar+2)){F=(F+6)}else{if(C.length>=(B.minchar+3)&&C.length<=(B.minchar+4)){F=(F+12)}else{if(C.length>=(B.minchar+5)){F=(F+18)}}}}if(C.match(/[a-z]/)){F=(F+1)}if(C.match(/[A-Z]/)){F=(F+5)}if(C.match(/\d+/)){F=(F+5)}if(C.match(/(.*[0-9].*[0-9].*[0-9])/)){F=(F+7)}if(C.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)){F=(F+5)}if(C.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){F=(F+7)}if(C.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){F=(F+2)}if(C.match(/([a-zA-Z])/)&&C.match(/([0-9])/)){F=(F+3)}if(C.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)){F=(F+3)}for(var D=0;D<B.common.length;D++){if(C.toLowerCase()==B.common[D]){F=-200}}return F}})})(jQuery) Sorry about the code i know its cluttered lol. I want to be able to put up files and assign passwords to individuals so that they can access one of those files but not all. In other words person A enters password & is redirected to file A; person B enters password & is redirected to file B, etc. Anyone have an example or know where I can get an example of a script like this? I am not a programmer so the simplier the better. Thanks
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... |