JavaScript - Having Trouble With Simple Validation Code..please Help
Similar TutorialsI'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. So frustrating that lately I've been having trouble with the simplest of code, and this is about as simple as it gets. Matched it up with every similiar example I can find both in books and on the net, and it seems to be perfectly valid code, but when I run it, nothing. :S 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>Untitled Document</title> <script language="javascript" type="text/javascript"> function favouriteColour() { var index = document.getElementById("select1").options[document.getElementById("select1").selectedIndex].value; document.getElementById = "Your favourite colour is " + index; } </script> </head> <body> <select id="select1"> <option></option> <option id="black" onchange="favouriteColour()">Black</option> <option id="white" onchange="favouriteColour()">White</option> <div id="favcolour"></div> <option> </select> </body> </html> Thanks in advance. Hello, and thank you for taking the time to read over my thread. I'm pretty new with Javascript coding and have been working with an example script for a new membership registration form. The original form seemed to have worked for most intents and purposes but it only contained one entry for a password field. Naturally I felt it needed a conformation field and have tried to stick one in, which is where I ran into problems. I successfully made the script throw an alert box if the two forms are the same, but it then throws another alert box of undefined function as well as throwing the same undefined function alert box even if the fields are a match. Hopefully a knowledgeable person could take a quick look at this and kindly inform me of where I'm going wrong? The code contains two of my numerous attempts to make it work (one commented out, it was easier to remember different things I have tried before to leave then in but commented out, I'm sure you all are quite familiar with that idea). Anyhow, here's the code, thank you in advance. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Register</title> <link href="css/master.css" rel="stylesheet" type="text/css" /> <style> .signup {border:1px solid #999999}</style> <script> function validate(form) { fail = validateFirstname(form.firstname.value) fail += validateSurname(form.surname.value) fail += validateUsername(form.username.value) fail += validatePassword(form.password.value) fail += validateConfirmpass(form.confirmpass.value) fail += validateAge(form.age.value) fail += validateEmail(form.email.value) if (fail == "") return true else { alert(fail); return false } } </script> <script> function validateFirstname(field) { if (field == "") return "No First name entered. \n" return "" } function validateSurname(field) { if (field == "") return "No Surname entered. \n" return "" } function validateUsername(field) { if (field == "") return "No Username was entered. \n" else if (field.length < 5) return "Usernames must be at least 5 characters. \n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ are valid in Usernames. \n" } function validatePassword(field) { if (field == "") return "No Password was entered. \n" else if (field.length < 6) return "Passwords must be at least 6 characters. \n" else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) || !/[0-9]/.test(field)) return "For your account security Passwords require atleast one uppercase, one lowercase, and one number to be valid. \n" } function validateConfirmpass() { var p1 = document.getElementById('password').value; var p2 = document.getElementById('confirmpass').value; if (p1 !== p2) alert("The password fields do not match."); } //function validateConfirmpass(field) { // var password = document.getElementById('password').value; // var confirmpass = document.getElementById('confirmpass').value; // if (password !== confirmpass) { // return "The password and confirmation do not match. \n" // } //} function validateAge(field) { if (isNaN(field)) return "No Age was entered.\n" else if (field < 18 || field >110) return "Age is required to be between 18 and 110 years. \n" return "" } function validateEmail(field) { if (field == "") return "No Email was entered. \n" else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address entered is invalid. \n" return "" } </script> </head> <body> <table class="signup" border="0" cellpadding="2" cellspacing="5"> <th colspan="2" align="center">Registration Form</th> <form method="post" action="tnssignup.php" onsubmit="return validate(this)"> <tr><td>First name</td><td><input type="text" maxlength="32" name="firstname" /></td> </tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td> </tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td> </tr><tr><td>Password</td><td><input type="text" maxlength="12" id="password" name="password" /></td> </tr><tr><td>Confirm Password</td><td><input type="text" maxlength="12" id="confirmpass" name="confirmpass" /></td> </tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td> </tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td> </tr><tr><td colspan="2" align="center"> <input type="submit" value="Register" /></td> </tr></form></table> </body> </html> Hello, I'm trying to make a simple webpage with two input text boxes that when submitted when empty, I'll get an error pop-up telling me which ones are empty, both, first name, or last name. When there's only one if, the script works. But when there's multiple else ifs, nothing happens if I press submit. Can someone help me? Code: <html> <head> <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["firstname"].value; var y=document.forms["myForm"]["lastname"].value; if (x==null || x=="" && y==null || y=="") { alert("Please put in your first and last name."); return false; } else if (x==null || x=="") { alert("Please put in your first name."); return false; } else if (y==null || y=="") { alert("Please put in your last name."); return false: } } </script> </head> <body> <form name="myForm"> First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"> <input type="submit" value="Submit" onclick="validateForm()"> </form> </body> </html> Hi, thanks for taking the time to read this. I believe it is a very simple problem however I cannot get it to work, when I run it I enter info into the prompt and it seems to get stuck in a loop. Basically A prompt asks for user to enter a code (has to be either R or r or C or c) though when I enter one of those in it won't work. Code: <html> <head> <title>Water Usage</title> <script type="text/javascript"> // Setting our variables based on user input var code; var kl_c; var kl_r; var kl_c_cost; var kl_r_cost; code = prompt("Please Enter Code"); while ((code != "R") || (code != "C") || (code != "r") || (code != "c") || (code =="")) { alert("Please Enter C for Commercial or R for Residential"); window.location.reload(true); } if ((code == "C") || (code == "c")) { kl_c = prompt("Please Enter The Kilolitres Of Water Consumed"); kl_c_cost = (kl_c * 0.2) alert("The Total amount of water used for this Residential property is " + kl_c + " Kilolitres and the total cost is $" + kl_c_cost); } else if ((code == "R") || (code == "r")) { kl_r = prompt("Please Enter The Kilolitres Of Water Consumed"); kl_r_cost = (kl_r * 0.6) alert("The Total amount of water used for this Residential property is " + kl_r + " Kilolitres and the total cost is $" + kl_r_cost); } </script> </head> <body> </body> </html> Can some please help me. I'm really new at this and is having trouble with this simple example Code: <html> <head> <script type="text/javascript"> //Below i was trying to set up a var pam that includes some text //and the value of form field name pamcheck and then display that result of pam on the screen //using a check box with a value of 'pale ale malt' hoping that when the ckeck box is checked //and then user clicks submit the result would be displayed on the screen as // 'Your selected malt is Pale ale malt' function pamff1() { pam = ("<p>Your selected malt is <p>" + pamcheck); document.write(pam); } </script> </head> <body> <form onsubmit="pamff1();"> <input type="checkbox" name="pamcheck" value="Pale ale malt" > <input type="submit" value="Submit"> </form> </body> </html> Hello.. I'm in a Web Development basics class at my College. We are about two weeks in as we've blew through HTML and CSS. Anyway.. to the question. So for this class I need to make a website with terms and their definitions. The definitions have to be in Javascript and make them show up with an alert. The problem is, I can't figure out how to have unique functions that I can somewhat link with the button. Quote: <html> <head> <script type="text/javascript"> function show_alert() { alert('term definition ONE ') } </script> </head> <body> <input type="button" value="term definition ONE " onclick="show_alert()" /> <input type="button" value="term definition TWO " onclick="show_alert()" /> </body> </html> Making a new button would just link to the script that's in the <head> giving the same definition. It's almost like I need to give each function a variable that matches up with each button, since I have multiple terms.. I hope you get what I'm trying to say. I'm trying to create a type of virtual pagination that's simple, semantic, and SEO friendly. The concept is like this website: www.doner.com In the bottom right hand corner, if you select a city, different contact information appears. My theory is to assign a class name to the hyperlink, then have a DIV with a matching ID. For example... Code: <a href="#" class="michigan">Michigan</a> <a href="#" class="ohio">Ohio</a> <a href="#" class="illinois">Illinois</a> <div id="michigan"> Michigan container </div> <div id="ohio"> Ohio container </div> <div id="illinois"> Illinois container </div> The JavaScript I have written so far is... Code: var anchor = document.getElementsByTagName('a').className; // grab all hyperlinks and their classes var div = document.getElementsByTagName('div').getElementByID; // grab all divs and their IDs if (anchor = div) { // check to see if a hyperlink's class has a matching div ID div.style.display = "none"; if (anchor.onclick) { // if the hyperlink is clicked... div.style.display = "visible"; // make matching div ID visible } } Nothing works yet, and I don't know where to continue. The DIVs aren't even hidden upon loading. Can anyone help me? Hi 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; } } 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? 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. 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 I am trying to set up a looping structure that tests to see if the user enters a value. If the textbox is null then a global variable is false otherwise a checkbox is checked and the global variable is true. below is what i have done so far, please assist me. var isValid = false; window.onload = startForm; function startForm() { document.forms[0].firstName.focus(); document.forms[0].onsubmit = checkEntries; alert("You have been added to the list") } function checkEntries() { var menus = new Array(); var formObject = document.getElementsByTagName('*'); for (var i=0; i < formObject.length; i++){ if (formObject[i] == "myform") menus.push(formObject[i]); if (document.forms[0].firstName.value.length==0 || document.forms[0].firstName.value.length == null){ isValid= false; alert("Please enter a first name"); } else (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].lastName=="" || document.forms[0].lastName== null){ alert("Please enter a last name"); isValid = false; } else (document.forms[0].check1.checked=true); isValid=true; if (document.forms[0].email=="" || document.forms[0].email== null) { alert("Please enter a valid email"); } else return (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].bDate=="" || document.forms[0].bDate== null) { isValid=false; alert("please make sure you enter a valid birth date."); } else (document.forms[0].check0.checked=true); isValid=true; } } here is the form html... <form name="myform" > <input type="checkbox" name="check0" class="check0" id="check0" > First: <input type="text" name="firstName" id="firstName"> <BR> <input type="checkbox" name="check1" class="check1" id="check1" > Last: <input type="text" name="lastName" id="lastName" ><BR> <input type="checkbox" name="check2" class="check2" id="check2" > E-Mail: <input type="text" name="email" id="email"> <BR> <input type="checkbox" name="check3" class="check3" id="check3" > Birthday (mm/dd/yyyy): <input type="text" name="bDate" id="bDate"> <BR> <input type="submit" value="Join our mailing List" /> </form> I'm trying to do a simple validation to see if the field is blank, if it is, I want to write a message to a div. I've added the function call to an onclick. It seems to be set off no matter if there is a value or not, and what's more, the fields are clearing out when the link is clicked. My brain is mush right now, so what am I missing? Code: function validateThis() { document.getElementById('messages').innerHTML = '' var theMessage = ''; var reqMsg = 'must have a value.'; for (var i = 0; i <document.theForm1.elements.length; i++) { if (document.theForm1.elements[i].value = ' ') { theMessage += document.theForm1.elements[i].name +' ' + reqMsg +'<br/>'; }} document.getElementById('messages').innerHTML = theMessage; } Hi I am trying to 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; } 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> |