JavaScript - Problem With Simple Validation Script
Having an unusual problem with the simple validation script below. In my script, I want to validate the username text field so that if the value of the text field (i.e. the amount of characters in the field) is less than 5, it would show a message in the page using innerHTML. The script works, but in a roundabout sort of way, or at least that's what it seems to me. Instead of making sure that the amount of characters in the text field is less than 5, it seems to disregard this entirely and instead make it so that if it has no value at all, the message will be shown. If it has a value of even 1 character, though, the message does not show. Not what I was trying to do, and I really don't know what's happened.
Thanks in advance to anyone who can help out a newbie in need. Code: function uservalidate() { if (document.getElementById("user").value < 5) { document.getElementById("userdiv").innerHTML = "Username must be six characters or more." } else { document.getElementById("userdiv").innerHTML = "" } } Code: <body> <form id="form1"> <input type="text" id="user" onblur="uservalidate()" /> <div id="userdiv"></div> </form> </body> </html> Similar TutorialsHi folks this is my first post Edit: sorry for the incorrect title should have read simple javascript validation problem! i have a fair understanding of php and mysql and have never had to use javascript as i was secretly trying to avoid it. The time has now come where i want to use it for client side validation on a form. I am able to validate most of fields however i need to validate a date to check it has been entered in the following format dd/mm/yyyy and that the date is not greater than todays date. N.B the date is entered into a text field in HTML i wrote a function with lots of if/else statements and failed. Im 100% positive there is a far simpler way to achieve my goal any help would be greatly appreciated. Thanks Code: function checkDate(elem, helperMsg){ var day = elem.substr(0,2); var month = elem.substr(3,2); var year = elem.substr(6,4); if(day < 01 || day > 31) { var invalidday = true; } if (month < 0 || month > 12) { var invalidmonth = true; } if (year < 01 || year > 2099) { var invalidyear = true; } if ( month==04 || month==06 || month==09|| month==11) { if (day == 31) { var invalidday = true; } } if (month==02) { if (day > 28) { var invalidday = true; } } if (invalidday || invalidmonth || invalidyear) { alert(helperMsg); elem.focus(); return false; } else { var dd = today.getDate(); var mm = today.getMonth()+1;//January is 0! var yyyy = today.getFullYear(); if(dd < 10) { dd='0'+dd; } if(mm < 10) { mm='0'+mm; } } if (day > dd && month > mm && year > yyyy) { alert(helperMsg); elem.focus(); return false; } else { return true; } } I have two seperate js files. One that houses the functions mylibrary.js and another that call the validated functions myform.js. I can not get the form to validate any data. The data just sits there and will not report errors. Any help would be greatly appreciated. Code: function valForm() { if(!isAlpha(document.myform.firstname.value)) { myform.firstname.focus(); return false; } if(!validEmail(document.myform.email.value)) { myform.email.focus(); return false; } if(!isRequired1(document.myform.options.value)) { myform.options.focus(); return false; } return true; } // JavaScript Document seperate js file mylibrary.js function isNumber(num) { return !(/\D/.test(num)); } function isAlpha(text){ return text.match(/\w+/) } function validEmail(email){ return email.match(/^([a-zA-Z0-9]{3,})(((\.|\-|\_)[a-zA-Z0-9]{2,})+)?@([a-z]{3,})(\-[a-z0-9]{3,})?(\.[a-z]{2,})+$/i ) } function isRequired1(){ if(myform.food.selectedIndex ==0) { alert("Please select from the drop-down list."); } } Hey guys, so I am a designer (not a developer) doing a site for someone. I am playing with some simple free javascripts. I have lightbox and toggler. Both work great individually. They are conflicting and everywhere online says to set the both to onLoad in the body tag. Sounds easy enough. But I can't seem to figure out the call for this script: Code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="../js/expand.js"></script> <script type="text/javascript"> $(function() { $("h2.expand").toggler({method: "fadeToggle"}); }); //--><!]]> </script> <body onload="toggler();initLightbox()"> is what is seems like it should be for me. But that isn't working at all. Please help! I feel like I have tried every possible name with the toggler()... If you need more, I can point you to the site itself and you can see all of the (messy) code. Hi, everyone. I've been scratching my head about what's wrong with my script for awhile now. What I need to do is use the swapImages(id1,id2,id3) function to simply swap three images at an interval of 2 seconds. What happens with my script is that the first image shows up, and after 2 seconds, it switches to the next one. The problem is that the images start rapidly switching infinitely after those first two seconds. Could someone point out where the problem spot in my code is? Here's the code from my external js file: Code: function swapIt(id1,id2,id3) { var object1 = document.getElementById(id1); var object2 = document.getElementById(id2); var object3 = document.getElementById(id3); var z1 = object1.style.zIndex; var z2 = object2.style.zIndex; var z3 = object3.style.zIndex; object1.style.zIndex = z3; object2.style.zIndex = z1; object3.style.zIndex = z2; } Here's the code invoking this function in my html file: Code: function moveAvalon() { var x = xCoord("avalon"); if(x <= (W - 125)) { shiftIt("avalon", 10, 0); setInterval("moveAvalon()", 50); } else if(x > (W - 125)) { swapImages(); } } function swapImages() { showIt("kids"); showIt("fiction"); showIt("nfiction"); setInterval( 'swapIt("kids", "fiction", "nfiction")' , 2000); } i have this code included within a .php file on my website. I realised that my %age rules defining the width of my website page dont really work once i get to wider sizes so i want to use a fixed width page design using css code (only once wide enough) to achieve this. Please have a look at my code and tell me what im doing wrong i cant find anything wrong with my js. If js is anything like python i may need to change the output from a string to an integer or something along those lines. I can easily just doc.write the width but i cant get it to compare properly Code: <script type="text/javascript"> if (document.body.clientWidth > 1280) {document.write('<link href="wdestyle.css" rel="stylesheet" type="text/css" />')}; else {document.write('<link href="nrostyle.css" rel="stylesheet" type="text/css" />')}; </script> I am trying to have the page go to another page after clicking the submit button. is it possible to add to this function an else statement ? if form is filled then go to this page Code: function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); return false; } return true; } Code: if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailvalue)) this is a code to validate an email address. My question is.. how do you call this type of validation? Those /^\w+([\.-]?\w+.. i don't really understand how they work. Is there a special term used to describe this? I want to learn how it works. I want to search for tutorials online but i cant think of any desriptive word to use as keyword for google search. I cant find helpful results. Please help. Thanks Hey all, I'm finishing up a project at work that has a web-based front end. Our tightly compressed schedule has left me with no time to properly learn Javascript, so I need some help. I have two pages that need client side validation... Page 1: several text inputs, one select, one textarea, and (maybe) a checkbox There are some complex things I could do here, but for now, I just need to make users behave. The textarea must have something in it, certain select options need a Yes/No popup, and if the checkbox is written to the page (ASP determines this) then it must be checked before certain select options are submitted. I could copy some examples I've found, but how do I ignore the checkbox when it doesn't exist? Page 2: two selects and a textarea Options must be selected and the textarea must have something in it. Straightforward, except that it's a dynamic form where each element has a name + i where i is a number that increments each time the user expands the form. Will wildcards work here? I know this looks like "do my homework" but any help would be greatly appreciated. This is desired to work in IE6, but if that can't happen, I can force an IE8 upgrade on everyone. Hello all, I have had a look around the forums, but cannot find the answer that I am after. basically, I have a text area to enter a search, and I have already written the JavaScript part of it (unsure if this is where the problem lies). The text that will go into the text area is a URL. the search button is disabled if there are spaces in the query, or if the field is blank, else the button is enabled. The problem I'm having may or may not be to do with my script. The HTML is set to 'onKeyUp' and 'onBlur' to run the function. now, it works fine, unless the user uses the mouse to copy and paste a URL into the text area. the button remains disabled until the user focuses out of the text area then back in. if ctrl+v is used, then the function works. If you would like to see the script I have written let me know, I hope you have some ideas Thanks in advance! I have a simple validation script. The first line of the validation is: function Validate() { if (document.form.name.value == '') { the id of my form is form, so my query is will this validation work, as it does not have a name but it has an id. Should I change the name (above) to id? Would appreciate some help making some minor enhancements to a pet adoption form: http://pawsct.org/application.php Problem - Applicants don't read. They answer "No" to the "Agree to Shelter Visit" question, then fill out the looooong application, and get abusive when told that they're not eligible for adoption. They apply from Florida and ignore the warnings about the 90 mile limit. Text notes just don't make enough of an impact. I want to use OnChange to give an alert if someone does not answer "Yes" to agree to a shelter visit (i.e. popup "You must agree to a shelter visit to qualify for an adoption from PAWS") and perhaps a warning message (red text reminder about the 90 mile limit next to the drop-down box) if someone enters a state other than CT. Second problem - I'm a volunteer who doesn't know javascript and can't cobble together a SIMPLE, workable solution from other code samples. Any assistance that you can provide would be most welcome and appreciated. Note: we are planning a redesign of the web site and may do some more sophisticated form validation (e.g. check age, valid e-mail, valid phone) in the future. But for now, we're just looking to check a few key fields for answers that would immediately disqualify an applicant. I am a javascript begginer and would like to know what is this bit of code saying? (email.indexOf("@",atPos+1) > -1) Thank you! Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Email checker</title> <script type="text/javascript"> function validEmail(email) { invalidChars = " /:,;" if (email == "") { return false; } for (i=0; i<invalidChars.length; i++) { badChar = invalidChars.charAt(i) if (email.indexOf(badChar,0) > -1) { return false; } } atPos = email.indexOf("@",1) if (atPos == -1) { return false; } if (email.indexOf("@",atPos+1) > -1) { return false } periodPos = email.indexOf(".",atPos) if (periodPos == -1) { return false; } return true; } function submitIt(emailForm) { if (!validEmail(emailForm.emailAddr.value)) { alert("Invalid email address"); emailForm.emailAddr.focus(); emailForm.emailAddr.select(); return false } alert("email is correct!"); return true; } </script> </head> <body> <h2>Email checker</h2> <form onsubmit="return submitIt(this)" action="#"> Email Address: <input name="emailAddr" type="text" size="30" /> <p><input type="submit" value="Submit" /> <input type="reset" /></p> </form> </body> </html> Hi I am trying to valid a simple address, that works fine apart from the fact that it will not allow forward slash in it "/" such as: Unit 12/13 some where. In brief I want to change /^[\w ]+$/; to include a forward character in it. I am new to javascript. many thx. p.s. every time I google it they find me email address validation dehhhhh I use the following code: Quote: function validateVat_No(fld) { var error = ""; var illegalChars = /^[\w ]+$/; // allow letters, numbers, and spaces if (fld.value !== "") { if (!illegalChars.test(fld.value)) { fld.style.background = 'Yellow'; error = "The Vat No contains illegal characters.\n"; } } else { fld.style.background = 'White'; } return error; } I have used this formula before, for some reason it isnt working properly. If the value is equal to 0 it will give an alert and return false. Then if you change the value of the drop down it won't let you submit. Does anyone see anything wrong? Code: <script type="text/javascript"> <!-- function validate_form ( ) { valid = true; if ( document.week_picks.blowout.value == "0" ) { alert ( "Please Select a Blowout" ); } return false; } //--> </script> Code: <form name="week_picks" method="post" action="confirm.php" onsubmit="return validate_form()"> <select id="blowout" name="blowout"> <option value="0">..</option> .... </select> Thanks for any help. 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; } Hey there, trying to modify a basic JS validation script Ive been using for a couple of years to work on more than one form on a page, three in fact. JavaScript (in header) Code: <script type="text/javascript"> <!-- function validate_form () { valid = true; if ( document.form.name.value == "" ) { alert ( "Please enter your name" ); valid = false; } if ( document.form.phone.value == "" ) { alert ( "Please enter your phone number" ); valid = false; } return valid; } //--> </script> <script type="text/javascript"> <!-- function validate_form1 () { valid = true; if ( document.form1.name1.value == "" ) { alert ( "Please enter your name" ); valid = false; } if ( document.form1.email1.value == "" ) { alert ( "Please enter your email address" ); valid = false; } if ( document.form1.comment1.value == "" ) { alert ( "Please enter your message" ); valid = false; } return valid; } //--> </script> <script type="text/javascript"> <!-- function validate_form2 () { valid = true; if ( document.form2.name2.value == "" ) { alert ( "Please enter your name" ); valid = false; } if ( document.form2.phone2.value == "" ) { alert ( "Please enter your phone number" ); valid = false; } return valid; } //--> </script> and the forms... Code: <form class="cmxform" id="form" name="form" method="post" action="send.php" onsubmit="return validate_form ( );"> <input name="name2" class="custominput" id="name2" size="25" /> <input name="tel2" class="custominput" id="tel2" size="25" /> <input type="image" src="/send.png" alt="Submit Form" /> </form> <form class="cmxform" name="quoteForm" id="quoteForm" method="post" action="send.php" onsubmit="return validate_form1 ( );"> <input name="name" class="custominput" id="name" size="25" /> <input name="email" class="email custominput" id="cemail" size="25" /> <textarea id="comment" name="comment" cols="20" rows="2" class="customtextarea" ></textarea> <input type="image" src="send.png" alt="Submit Form" /> </form> <form class="cmxform" id="form2" name="form2" method="post" action="send.php" onsubmit="return validate_form2 ( );"> <input name="name2" class="custominput" id="name2" size="25" /> <input name="phone2" class="custominput" id="phone2" size="25" /> <input type="image" src="send.png" alt="Submit Form" /> </form> Ive stripped the forms down to the bones, they have default values set and onfocus commands in the full code. The problem Im having is rewriting the script above seems to work fine for the middle form but on the other two it tells me to input a valid name and then submts the form. Many thanks I'm trying to make an xhtml form that validates itself through a javascript function. I have the form up but for some reason I can't get it to validate. I'm not even sure if I linked things correctly. Here's what I have: the xhtml file <?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> <script src="gas24.js" type="text/javascript"></script> <h2> Registration Form </h2> <title> Javascript Form Validation Homework </title> </head> <body> <table border=""> <form name="validation_form" method="post" onsubmit="return validate()"> <tr> <td> <t>Name: <input type="text" name="YourName" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> E-mail Address: <input type="text" name="YourEmail" size="10" maxlength="24"/> </td> </tr> </br> <tr> <td> Password: <input type="password" name="YourPassword" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Re-Type Password: <input type="password" name="passwordConfirmed" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Your Gender: <input type="radio" name="MaleBox" Value="Male"> Male <input type="radio" name="FemaleBox" Value="Female"> Female </td> </tr> </br> <tr> <td> Comments: <input type="text" name="Comments" size="100" maxlength="500" value=""/> </td> </tr> <tr> <td> <input type="submit" value="Submit"/> </td> </tr> </form> </table> <p></p> </body> </html> The javascript file: I've tried two things. This: <SCRIPT LANGUAGE="JavaScript"> function validation() { var x=document.forms["validation_form"]["YourName"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } And this: function validation() if ( document.validation_form.YourName.value == "" ) { alert( "Please type your name."); valid = false; } if ( document.validation_form.YourPassword.value =! "document.validation_form.Confirm.value" ) { alert ( "Please confirm your password." ); valid = false; } I would greatly appreciate it if somebody could tell me what I'm doing wrong. |