JavaScript - Need Help With Simple Form Validation
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; } Similar TutorialsHey 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 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> 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; } 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. 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; } Hello, On my client's site: www.twdcycling.com he wanted a place where people could make suggestions for his blog. I accomplished the simple form using a textarea field and even put a little text that clears on clicks and reappears on blur. When you go there--go to the bottom left. It also actually works. The problem is that (besides the fact that so far no one has cared to make a suggestion) somehow the form is (this is what I believe) being submitted automatically. I don't believe a human is clicking submit. When I click submit w/o clicking in the field the default text that I have in the field already gets submitted in the generated email. So I now need to work on my validation in my php file that sends the email. For background I obtained my php file from html-form-guide.com here the file is in its entirety: Code: <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; //Validate first if(empty($name)||empty($visitor_email)) { echo "Name and email are mandatory!"; exit; } if(IsInjected($visitor_email)) { echo "Bad email value!"; exit; } $email_from = 'tom@amazing-designs.com';//<== update the email address $email_subject = "New Form submission"; $email_body = "You have received a new message from the user $name.\n". "Here is the message:\n $message". $to = "tom@amazing-designs.com";//<== update the email address $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; //Send the email! mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); // Function to validate against any email injection attempts function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } ?> It does have some validation code, and it also is set up to handle more parameters than I needed. I tried to just pare it down to the one simple thing (I just need the user to type anything they want into my text area) My reasoning is that I should be able to go get some simple validation snippet to make it so that if there is the possibility something is causing the form to just "fire off" w/o a human clicking, the validation shouldn't allow it to send, cause the text field is empty. But one would think if that is happening my default text would allow it to send, but oddly enough, no! when I get the email (last one at 5:49 am) it was a blank email! So its like some robot is doing two things: clicking in the field to empty it and THEN clicking submit! Weird, I know. But the validation code would fix this if only I knew how. (But on another note, if I try to send an empty box my default text pops back in when I click submit--proving that its happening automatically. I tried all morning yesterday to implement a snippet from several sources. Here's a couple of examples of what I added: Code: function emptyvalidation(entered, alertbox) { // Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } I didn't modify this code at all....maybe where I went wrong here. Should "value" correspond to text area name "message"? (about the only thing I didn't try) Here's another one --this one from W3 schools: Code: function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } this is how it was on the source site, all I changed was "myForm" and "fname" to "blog_suggestion" But when testing both these snippets separately what happened is that on submit I just go to my php page (which is just blank) I'm assuming code I'm adding is crashing the script somehow. And then of course no thank you page and no email sent. Finally here is my current php page in its entirety, followed by the form code on the home page... Code: <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $message = $_POST['message']; //Validate first if(empty($message)) { echo "Please enter a suggestion before clicking submit."; exit; } $email_from = 'f7digitaldesign@gmail.com';//<== update the email address $email_subject = "SOMEONE HAS SUBMITTED A SUGGESTION FOR THE BLOG!"; $email_body = "\n $message". $to = "f7digitaldesign@gmail.com";//<== update the email address $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . //Send the email! mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); // Function to validate against any email injection attempts function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } ?> I tried to modify the validation I got w/ this to produce the "echo" message "Please enter a suggestion before clicking submit." But let's be honest, by now you know I don't know what in the heck I'm doing (it doesn't seem to matter). Form code: Code: <form name="blog_suggetion" method="post" action="send_form_blogidea.php"> <span class="bloginfotext" ><textarea name="message" rows="14" cols="12" onfocus="clearValue(this, 'Please submit ideas for our blog here—we’d love to hear from you!')" onclick="this.value='';" onblur="if (this.value == '') {this.value = 'Please submit ideas for our blog here—we’d love to hear from you!';}" ></textarea></span> <div style="font-size:6px; color:#FFF;">sdsadfds</div> <input type="submit" name='submit' value="submit"> </form> Any time spent and help offered for this is greatly appreciated!! Also if you need to/want to test the field, I don't care--send me a message. I'll know someone cares! Brian Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript or how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. It'd be great if the submit button could be disabled until all fields are filled correctly, but I don't know if this is possible. Thanks in advance, and please let me know if it'll be possible. :) 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. I have built a signup form which has several text inputs and text areas. Their labels are set as their values. When the user focuses on the field, the label text is cleared to accept text input. When focus is changed to another field. The field checks if text has been entered. If it has not, it then resets the value back to the default label value. For example: Code: <input type="text" name="company_name" size="50" class="textInput" value="Company Name" onfocus="if(this.value=='Company Name')this.value='';" onblur="if(this.value=='')this.value='Company Name';" /> What I would like to do is have some simple javascript which checks the fields on submit. If any of the required fields still have the default label value, then I would like to change the colour of the label value in the input to red and disable the form submit until the value is corrected. Most of the inputs and text areas will accept any text, though one is an email text input. I don't think any fancy validation is needed for this email input , other than checking to be sure a '@' has been entered. Since the website that this form will be contained in runs jQuery, I have looked into some plugins for form validation. However, these seem to be over-complicated for what I need. I want to keep this as simple and light as possible. Oh, and also, I am not allowed to use anything php based as this is not allowed to run on our servers for security reasons... Any advice or suggestions are much appreciated! Hello all, new here Seems like a very nice place to be apart of. I have my website www.gebcn.com. If you view source you will see all that I have done, but more importantly my problem. I have the JS code at the top there and I am unable to W3C validate my HTML because of the JS. I am using XHTML strict and would like to stay using it. The JS I have at the top is my form validation code. I am able to do any validating that I need with this "snippet" of code, I have shrank it from my library version just to use for this newsletter. Until now W3C validating was not important now for some reason it is and I am faced with this problem. I am not a Javascript guy more of a HTML/CSS guy and I can manipulate JS to suit my needs. <problem> I have tried to make this "snippet" of JS code an external file but receive multiple errors with the JS calling for the FORM NAME as it is not on the same page. The form NAME=NEWSLETTER is another problem, as W3C says I am unable to use attribute "NAME" in this location. <problem> I would like to keep the JS close to how it is now as I have a library to use this JS over and over again. Any pointers in the right direction or solutions to my problem would be greatly appreciated. Thanks! Hopefully it is not to hard huh If there is anything anyone needs, the code pasted here, or anything else please let me know. Thanks again! 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? 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; } } 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 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 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. 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> |