JavaScript - Registration Validation
This is a bit of a lazy post but hey,
Currently i have an awful lot of checks that run the same check on different variables. Simple Request... Can anyone see an obvious way (which i have clearly missed) to clean up and reduce the amount of code in the below. Code: <? // required code for every page. require($_SERVER['DOCUMENT_ROOT'] . '/scripts/required.php'); // end of required code for every page if(isset($_POST['sbmt'])) { // get variables $new_user = trim($_POST['user']); $new_pass = $_POST['newpass']; $con_pass = $_POST['conpass']; $new_fname = trim($_POST['fname']); $new_email = $_POST['email']; $con_email = $_POST['conemail']; $agree = $_POST['agree']; $level = $_POST['level']; $ip = @$_SERVER['REMOTE_ADDR']; // add slashes $new_user = addslashes($new_user); // encrypt $new_pass_e = hash('ripemd160',$new_pass); $con_pass_e = hash('ripemd160',$con_pass); // check username exists // connect to database $con = mysql_connect(DBHOST, DBUSER, DBPASS); if(!$con) { die('Could not connect: ' . mysql_error());} mysql_select_db(DBNAME, $con); // get row for user $result = mysql_query("SELECT * FROM tUsers WHERE username='$new_user'"); $row = mysql_fetch_array($result); // kill connection mysql_close($con); // check username exists if($row['username']!=null) $user_error = 'Username already in use.<br />'; else $user_error = null; // check email is available // connect to database $con = mysql_connect(DBHOST, DBUSER, DBPASS); if(!$con) { die('Could not connect: ' . mysql_error());} mysql_select_db(DBNAME, $con); // get row for user $result = mysql_query("SELECT * FROM tUsers WHERE email='$new_email'"); $row = mysql_fetch_array($result); // kill connection mysql_close($con); // check email is available if($row['email']!=null) $email_error = 'Email already in use.<br />'; else $email_error = null; // check lengths if(strlen($new_user)<3) $user_len_error = 'Username must be at least 3 characters<br />'; else $user_len_error = null; if(strlen($new_pass)<6) $pass_len_error = 'Password must be at least 6 characters<br />'; else $pass_len_error = null; if(strlen($new_fname)<6) $fname_len_error = 'Your name must be at least 6 characters<br />'; else $fname_len_error = null; // preg matches if(!preg_match('/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $new_email)) $email_preg_error = "Email is not valid.<br />"; else $email_preg_error = null; if(!preg_match('/[a-zA-Z]+\s+[a-zA-Z]+/',$new_fname)) $fname_preg_error = 'Name must containt at least one space.<br />'; else $fname_preg_error = null; // check matches if($new_pass != $con_pass) $pass_match_error = 'The passwords do not match.<br />'; else $pass_match_error = null; if($new_email != $con_email) $email_match_error = 'The emails do not match.<br />'; else $email_match_error = null; // build error list $errorlist = $user_error; $errorlist .= $email_error; $errorlist .= $user_len_error; $errorlist .= $pass_len_error; $errorlist .= $fname_len_error; $errorlist .= $email_preg_error; $errorlist .= $fname_preg_error; $errorlist .= $pass_match_error; $errorlist .= $email_match_error; // set expirey to a month $expire = 0; // set error list cookie setcookie('errorlist',$errorlist,$expire,'/'); // reload register.php header('Location:' . URL . '/register.php'); } ?> The required file is just a series of defines for items like the dbhost, dbusername, dbname, url etc etc. Cheers p.s. I want to add an if statement for if $errorlist=null then do bla else bla... in order for errorlist to be null... do i actually need to define the individual error messages as null. That could get rid of a lot of: else $<error name>=null; I'm pretty sure I can but i'd like to check first. Similar Tutorials<?php require('connect.php'); if($_POST['reg1']=="Register") { $stmt1="insert into regtable(fname,lname,c_addr,p_addr,phno,email,dob,gender,qual,wexp,usertype,btype,uname,pwd) values('$name1','$name2','$add1','$add2','$phno1','$email1','$dob1','$gend1','$qual1','$wexp1','$uty pe','$batch1','$user','$upwd')"; $res1=mysql_query($stmt1,$con);} ?> <html> <head> <script type="text/javascript"> function validate() { f=0; if(document.getElementById('fname').value=="") { document.frm1.fname.style.border='1px solid red'; //document.frm1.fname.style.background='#FFFFCC'; document.frm1.fname.focus(); document.getElementById('d_fname').style.visibility="visible"; document.getElementById('d_fname').innerHTML="Enter First Name"; } else { f++; } if(document.getElementById('lname').value=="") { document.frm1.lname.style.border='1px solid red'; document.frm1.lname.focus(); document.getElementById('d_lname').style.visibility="visible"; document.getElementById('d_lname').innerHTML="Enter Last Name"; } else { f++; } if(document.getElementById('addr1').value=="") { document.frm1.addr1.style.border='1px solid red'; document.frm1.addr1.focus(); document.getElementById('d_cadd').style.visibility="visible"; document.getElementById('d_cadd').innerHTML="Enter Contact Address"; } else { f++; } if(document.getElementById('pno').value=="") {document.frm1.pno.style.border='1px solid red'; document.frm1.pno.focus(); document.getElementById('d_pno').style.visibility="visible"; document.getElementById('d_pno').innerHTML="Enter Phone Number"; } else { f++; } if(document.getElementById('emid').value=="") {document.frm1.emid.style.border='1px solid red'; document.frm1.emid.focus(); document.getElementById('d_emid').style.visibility="visible"; document.getElementById('d_emid').innerHTML="Enter Email Id"; } else {f++; } if(document.getElementById('day').value=="0") { document.frm1.day.style.border='1px solid red'; document.getElementById('d_dob').style.visibility="visible"; document.getElementById('d_dob').innerHTML="Invalid Date"; } else { f++; } if(document.getElementById('month').value=="0") { document.frm1.month.style.border='1px solid red'; document.getElementById('d_dob').style.visibility="visible"; document.getElementById('d_dob').innerHTML="Invalid Date"; } else { f++; } if(document.getElementById('year').value=="0") { document.frm1.year.style.border='1px solid red'; document.getElementById('d_dob').style.visibility="visible"; document.getElementById('d_dob').innerHTML="Invalid Date"; } else {f++; } if((document.getElementById("gender1").checked!=true) && (document.getElementById("gender2").checked!=true)) { //document.frm1.gender.style.border='1px solid red'; document.getElementById('d_gender').style.visibility="visible"; document.getElementById('d_gender').innerHTML="Select Gender"; } else { f++; } if((document.getElementById("qual1").checked!=true) && (document.getElementById("qual2").checked!=true) && (document.getElementById("qual3").checked!=true) && (document.getElementById("qual4").checked!=true)) { //document.frm1.gender.style.border='1px solid red'; document.getElementById('d_qual').style.visibility="visible"; document.getElementById('d_qual').innerHTML="Select Qualification"; } else {f++; } if(document.getElementById('wexp').value=="") { document.frm1.wexp.style.border='1px solid red'; //document.frm1.emid.focus(); document.getElementById('d_wexp').style.visibility="visible"; document.getElementById('d_wexp').innerHTML="Select Work Experience"; } else {f++;} if(document.getElementById('utype').value=="") { document.frm1.utype.style.border='1px solid red'; document.getElementById('d_utype').style.visibility="visible"; document.getElementById('d_utype').innerHTML="Select Usertype"; } else {f++; } if(document.getElementById('btype').value=="") { document.frm1.btype.style.border='1px solid red'; //document.frm1.emid.focus(); document.getElementById('d_btype').style.visibility="visible"; document.getElementById('d_btype').innerHTML="Select Batch"; } else {f++; } if(document.getElementById('uname').value=="") { document.frm1.uname.style.border='1px solid red'; document.frm1.uname.focus(); document.getElementById('d_uname').style.visibility="visible"; document.getElementById('d_uname').innerHTML="Enter Username"; } else {f++; } if(document.getElementById('pwd').value=="") { document.frm1.pwd.style.border='1px solid red'; document.frm1.pwd.focus(); document.getElementById('d_pwd').style.visibility="visible"; document.getElementById('d_pwd').innerHTML="Enter Password"; } else {f++; } if(document.getElementById('rpwd').value=="") { document.frm1.rpwd.style.border='1px solid red'; document.frm1.rpwd.focus(); document.getElementById('d_rpwd').style.visibility="visible"; document.getElementById('d_rpwd').innerHTML="Retype Password"; } else { f++; } if(f==15) {return true;} else { return false;} } /*function nameval() { var fnm=document.getElementById('fname').value; var pat=/\d\g; if(fnm.match(pat)) { alert("Only characters are allowed"); } }*/ function phonval() { var ph=document.getElementById("pno").value; var pat=/\s/g; var ex=/\D/g; str=""; if(ph.match(ex)) { // alert ("Invalid Phone"); str=str+ "Phone number should be digits"; document.getElementById('pno').value=""; } else if(ph.length!=10) { str=str+"Phone number should be of 10 digits" //alert("Phone number should be of 10 digits"); } /*else if(ph.match(pat)) { str=str+"Phone number cannot have blank spaces"; //alert("Phone number cannot have blank spaces"); } */ if(str.length!=0) { alert(str);} } function emailval() { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.getElementById('emid').value; if(reg.test(address) == false) { alert('Invalid Email Address'); return false; } } </script> </head> <body id="www-url-cz" onload="inactive()"> <h2><img src="design/icon-registration.png" height="70px" \>Registration Form</h2> <form name="frm1" method="post"> <table style="padding-top:50px;"> <tr> <th align="left">First Name</th> <td><input type="text" name="fname" id="fname" size="27" class="border"></td> <td class='err'><div id="d_fname"></div></td> </tr> <tr></tr> <tr> <th align="left">Last Name</th> <td><input type="text" name="lname" id="lname" size="27" class="border"></td> <td class='err'><div id="d_lname"></div></td> </tr> <tr></tr> <tr> <th align="left">Contact Address</th> <td><textarea rows="5" cols="20" name="addr1" id="addr1" class="border"></textarea></td> <td class="err"><div id="d_cadd"></div></td> </tr> <tr></tr> <tr> <th align="left">Permanent Address</th> <td><textarea rows="5" cols="20" name="addr2" id="addr2" class="border"></textarea></td> <td class='err'><div id="d_padd"></div></td> </tr> <tr></tr> <tr> <th align="left">Phone Number</th> <td><input type="text" name="pno" id="pno" size="27" class="border" onblur="phonval()"></td> <td class='err'><div id="d_pno"></div></td> </tr> <tr></tr> <tr> <th align="left">Email id</th> <td><input type="text" name="emid" id="emid" size="27" class="border" onblur="return emailval()"></td> <td class='err'><div id="d_emid"></div></td> </tr> <tr></tr> <tr> <th align="left">Date of Birth</th> <td colspan="3"> <select name="day" id="day" class="border" onchange="dat_day()"> <option value="0">Day</option> <script type="text/javascript"> for(i=1;i<=31;i++) { document.write("<option value="+i+">"+i+"</option>"); } </script> </select> <select name="month" id="month" class="border" onchange="dat_month()"> <option value="0">Month</option> <option value="1">Jan</option> <option value="2">Feb</option> <option value="3">Mar</option> <option value="4">Apr</option> <option value="5">May</option> <option value="6">June</option> <option value="7">Jul</option> <option value="8">Aug</option> <option value="9">Sep</option> <option value="10">Oct</option> <option value="11">Nov</option> <option value="12">Dec</option> </select> <select name="year" id="year" class="border" onchange="dat_year()"> <option value="0">Year</option> <script type="text/javascript"> for(i=1975;i<=1996;i++) { document.write("<option value="+i+">"+i+"</option>") } </script> </select><div class="err" id="d_dob"></div> </td> <!--<td class="err"><div id="d_dob"></div></td>--> </tr> <tr></tr> <!--<tr> <th align="left">Age</th> <td><input type="text" name="age id="age" size="27" class="border"></td> </tr>--> <tr> <th align="left">Gender</th> <td colspan="3"> Male<input type="radio" value="male" name="gender" id="gender1"> Female<input type="radio" value="female" name="gender" id="gender2"> <div class="err" id="d_gender"></div> </td> <!--<td class='err'><div id="d_gender"></div></td>--> </tr> <tr></tr> <tr> <th align="left">Qualification</th> <td colspan="5"> SSLC<input type="radio" value="sslc" name="qual" id="qual1"> Plus Two<input type="radio" value="plus_two" name="qual" id="qual2"> Degree<input type="radio" value="degree" name="qual" id="qual3"> PG<input type="radio" value="pg" name="qual" id="qual4"> <div class="err" id="d_qual"></div> </td> <!--<td class='err'><div id="d_qual"></div></td>--> </tr> <tr></tr> <tr> <th align="left">Work Experience(in years)</th> <td colspan="2"><select name="wexp" id="wexp" class="border"> <option value=''>Select One</option> <script type="text/javascript"> for(var i=0;i<=15;i++) { document.write("<option value="+i+">"+i+"</option>"); } </script> <option>More than 15 years</option> </select> <div id="d_wexp" class="err"></div> </td> <!--<td class='err'><div id="d_wexp"></div></td>--> </tr> <tr></tr> <tr> <th align="left">User Type</th> <td><select name="utype" id="utype" class="border"> <option value=''>Select One</option> <option value='admin'>Administrator</option> <option value='trainer'>Trainer</option> <option value='trainee'>Trainee</option> </select> </td> <td class='err'><div id="d_utype"></div></td> </tr> <tr></tr> <tr> <th align="left">Batch Type</th> <td><select multiple="multiple" size="0" name="btype" id="btype" class="border"> <option value=''>Select One</option> <?php while($row=mysql_fetch_array($result)) { ?> <option value="<?php echo $row['batchtypeid']?>"><?php echo $row['batchtype'] ?></option> <?php } ?> </select> </td> <td class='err'><div id="d_btype"></div></td> </tr> <tr></tr> <!-- <tr> <th align="left">Batch Code</th> <td> <select multiple="multiple" size="0" name="bcode" id="bcode" class="border">--> <!--<option value="">Select One</option>--> <!--</select> </td> <td class='err'><div id="d_bcode"></div></td> </tr>--> <tr></tr> <tr> <th align="left">Username</th> <td><input type="text" name="uname" id="uname" size="27" class="border"></td> <td class='err'><div id="d_uname"></div></td> </tr> <tr></tr> <tr> <th align="left">Password</th> <td><input type="password" name="pwd" id="pwd" size="27" class="border"></td> <td class='err'><div id="d_pwd"></div></td> </tr> <tr></tr> <tr> <th align="left">Retype Password</th> <td><input type="password" name="rpwd" id="rpwd" size="27" class="border"></td> <td class='err'><div id="d_rpwd"></div></td> </tr> <tr> <td></td> </tr> <tr></tr> <tr> <td></td> <td><input type="submit" value="Register" name="reg1" id="reg1" onclick="return validate()" ></td> </tr> </table></form></div> Hey all. I have a simple validation I need to do. I need to just make sure that a Checkbox is checked, and that a Text field has content. Sounds simple but I cannot find any thing that has a check and a text field. Here what I have. Can I modify this script to do this? A Checkbox MUST be checked and Text field MUST be filled out. This currently does the text field fine, but no Checkbox obviously. How can I add a checkbox validation to this? Thats it. Any help is appreciated. Code: <script type="text/javascript"> var textFields = ["digsig"]; function validateForm( ) { var oops = ""; // must initialize this! var form = document.sig; for ( var t = 0; t < textFields.length; ++t ) { var field = form[textFields[t]]; var value = field.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim the input if ( value.length < 1 ) { oops += "You MUST enter your Digital Signature"; } } if ( oops != "" ) { alert("ERROR:" + oops); return false; } } } </script> Sup gents Can someone please tell me whats wrong with this code? The user is supposed to input a pass and script needs to check the array to see if such a pass exists in the array and confirm. Im building a sign in system for my website and this is the first step. Dont mind the global values in the beginning i plan to use them later while applying restrictions. Code: <html> <head> <script type ="text/JavaScript"> var counter = 0; var trial = 0; var base = 0; var choice = 0; var array2[] = {"1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009"}; var searchKey = searchform.inputVal.value; function pass() { for (var i =0; i < array2.length; i++) { if (array2[i] == searchkey ) searchform.result.value = "correct password"; } else return -1; } </script> </head> <body> <form name = "searchform" action = ""> <p>Enter password<br /> <input name = "inputVal"/> <input name = "search" type = "button" value = "Search" onclick = "pass()" /><br /></p> <p>Result<br /> <input name = "result" type = "text" size = "30" /></p> </form> </body> </html> Hello, i got a problem with form like this: https://www2.giocarena.com/it-IT/Register/Start.aspx It's possible to set the field Cod Referent????? I've tried with this: <form name="aspForm" method="post" action="https://www2.giocarena.com/it-IT/Register/Start.aspx" target="_blank"> <input type="hidden" name="ctl00$cphBaseContainer$ctl00$txt_code" value="44411122224322445"></input> <button type="submit"> Nome </button> </form> Thank you!Thank you, thank you! Anybody help to start out this code: Create a "nag" counter that tells users to register. Save the counter in a cookie and display a message reminding users to register every fifth time they visit your site. There are four other parts to this task that I know how to do. I cannot find anything close to this in our book referencing a nag-counter or something similar to it. Thanks, in advance. Regards, AO5431 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! I have a piece of JavaScript code that should validate that a username field is not empty or null and that a telephone field is in the correct format using event handler registration. It seems to be validating fine but if there is an error it still manages to submit. HTML Code: <html> <head> <script type = "text/javascript" src = "js/validator.js" > </script> </head> <body> <form id = "decorForm" action = ""> <table border = "0"> <tr> <th>Username: </th> <td> <input type = "text" id = "myUserName" size = "15" maxlength = "15"/> </td> </tr> <tr> <th>Telephone: </th> <td> <input type = "text" id = "telephone" name = "telephone" size = "15" maxlength = "13"/> <br /> (999)999-9999 </td> </tr> <tr> <td> <input type = "submit" value = "Submit" /> </td> <td> <input type = "reset" value = "Reset" /> </td> </tr> </table> </form> <script type = "text/javascript" src = "js/validatorr.js" > </script> </body> </html> JAVASCRIPT (validator.js) Code: function chkUser() { // Verifies that the UserName field is not empty. var myUserName = document.getElementById("myUserName"); if (myUserName.value == "" || myUserName.value == null) { alert ("Please enter a Username!"); return false; } else { return true; } } function chkTelephone() { // Verifies that the Telephone field value is in the correct format. var tel = document.getElementById("telephone"); var pos = tel.value.search(/^\(\d{3}\)\d{3}-\d{4}$/); if (pos != 0) { alert ("Please enter telephone number in the following format: (999)999-9999"); return false; } else { return true; } } function chkFields() { // Verifes all fields and returns boolean to event handler // The event handler function if (chkUser() && chkTelephone()) { return true; } else { return false; } } JAVASCRIPT (validatorr.js) Code: //Register the event handlers for validator.js document.getElementById("decorForm").onSubmit = chkFields; I am trying to use this as an example. Hey. Could someone point me in the direction of why this is not working, it worked in my last program, but not since I have changed things. I have a standard html form Code: <form method="POST" onsubmit="return validate_form(this)" action="anniversaryPreview.php"> <p class="demo5">Senders Name<a class="textFields2"> <input type="text" name="sender" value="e.g. Love from Nick" size="30" maxlength="35" /></a></p> <p class="btn2" > <input type="submit" value="Preview"></p> </form> And this should call up return validate_form(this) before bringing up the php page. Now the validator is just Code: function validate_required(field, alerttxt) { if (field.value == null || field.value == "") { alert(alerttxt); return false; } else { return true; } } function validate_form(thisform) { if (validate_required(thisform.name,"Please specify the receivers name.")==false) { thisform.name.focus(); return false; } if (validate_required(thisform.sender,"Please specify the sender's name.")==false) { thisform.sender.focus(); return false; } } (This is not in the html file, but its own seperate file) I cant see if I have made any mistakes with the variables names or something, or what I am doing wrong. Dont get any errors, just nothing happens if I leave my forms fields blank. Anyone have an idea of whats going on here? cheers Hello to everyone i need to validate a form Based on radio buttons and text box my code so far Code: <html> <head> <title>My Page</title> <script type="text/javascript"> function validate(thisform) { document.getElementByName("bank");//text box // validate myradiobuttons radio = -1; for (i=thisform.day.length-1; i > -1; i--) { if (thisform.day[i].checked) { radio = i; i = -1; } } if (radio == -1) { alert("You must select all values for the clock !"); return false; } else { return true; } } //bank code validation if (document.getElementByName("bank").value.length>=6) { return true; } else { alert("you must input maximum 6 digit (123456) !"); return false; } } </script> </head> <body> <form action="form-output.php" method="post" id="form"> <input type="radio" name="day" value="f" onclick="dayofweek(this)" /> Sunday (default) <input type="radio" name="day" value="s" onclick="dayofweek(this)" /> Sun </p> <input type="radio" name="month" value="a" onclick="dateformat(this)" /> 28th March 2010 (default) <input type="radio" name="month" value="b" onclick="dateformat(this)" /> 28 March 2010 <input type="radio" name="month" value="c" onclick="dateformat(this)" /> 28th Mar 2010 <input type="radio" name="month" value="d" onclick="dateformat(this)" /> 28 Mar 2010 <input type="radio" name="month" value="e" onclick="dateformat(this)" /> 28/03/2010 <input type="radio" name="month" value="f" onclick="dateformat(this)" /> 28th March 10 <input type="radio" name="month" value="g" onclick="dateformat(this)" /> 28 March 10 <input type="radio" name="month" value="h" onclick="dateformat(this)" /> 28th Mar 10 <br/> <input type="radio" name="month" value="i" onclick="dateformat(this)" /> 28 Mar 10 <input type="radio" name="month" value="j" onclick="dateformat(this)" /> 28/03/10 <input type="radio" name="month" value="k" onclick="dateformat(this)" /> 28th March <input type="radio" name="month" value="l" onclick="dateformat(this)" /> 28 March <input type="radio" name="month" value="m" onclick="dateformat(this)" /> 28th Mar <input type="radio" name="month" value="o" onclick="dateformat(this)" /> 28 Mar <input type="radio" name="month" value="p" onclick="dateformat(this)" /> 28/03 </p> <input type="radio" name="time" value="a" onclick="timeformat(this)" /> 5:28:12 am (Default) <input type="radio" name="time" value="b" onclick="timeformat(this)" /> 5:28 am <input type="radio" name="time" value="c" onclick="timeformat(this)" /> 5:28:12 <input type="radio" name="time" value="d" onclick="timeformat(this)" /> 5:28 <input type="radio" name="time" value="e" onclick="timeformat(this)" /> 17:28:12 <input type="radio" name="time" value="f" onclick="timeformat(this)" /> 17:28 </p> Input a short Bank Code <input type="text" name="bank" size="10" onblur="JavaScript:alert('You must insert a Bank Code')" /></br> <input type="submit" name="submit" onclick="validate(form);return false;" value="Submit" /> <input type="reset" name="reset" value="reset" /> </form> </body> </html> i need on submit to validate if user select values from 3 radio groups and insert the proper data to text box. if not i want to return the proper alerts in text box also i want when lose focus to validate so i put this Code: onblur="JavaScript:alert('You must insert a Bank Code')" it's ok? Thanks in Advance Hi, got my form here Code: <form method="POST" onsubmit="return validateFormOnSubmit1(this)" action="sendEmail.php"> <p class="demo2">Receivers E-mail<a class="textFields"> <input type="text" name="receiver" size="30" maxlength="35" /></a></p> <p class="demo2">Senders E-mail<a class="textFields2"> <input type="text" name="sender" size="30" maxlength="35" /></a></p> <p class="btn" > <input name="Submit" type="submit" value="Send"/></p> </form> And that should call up this Code: function validateFormOnSubmit1(theForm) { var reason = ""; reason += validateEmail1(theForm.receiver); reason += validateEmail1(theForm.sender); if (reason != "") { alert("Some fields need correction:\n" + reason); return false; } return true; } function trim(s) { return s.replace(/^\s+|\s+$/, ''); } function validateEmail1(fld) { var error=""; var tfld = trim(fld.value); // value of field with whitespace trimmed off var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; if (fld.value == "") { fld.style.background = 'Yellow'; error = "You didn't enter an email address.\n"; } else if (!emailFilter.test(tfld)) { //test email for illegal characters fld.style.background = 'Yellow'; error = "Please enter a valid email address.\n"; } else if (fld.value.match(illegalChars)) { fld.style.background = 'Yellow'; error = "The email address contains illegal characters.\n"; } else if (fld.value.length == 0) { fld.style.background = 'Yellow'; error = "The required field has not been filled in.\n" } else { fld.style.background = 'White'; } return error; } For some reason though the validation is not working. Is there anything obvious I am doing wrong? cheers Hi All, I have a java script invoked within an ANT template. This java script as of now converts a text file to xml file. Now, how would I do the schema validation of that XML file against an XSD in the javascript? Saw many examples online but they were using MSXML or java classes Would be glad to have any sort of suggestions.. Thanks In my project i have a from which have several fields. The form is <form name="reg" action="payment.jsp" method="post"> ----------- <tr> <td>First name:</td> <td><input type="text" name="firstname"/></td></tr> -------------------------- <input type="submit" value="Next" onclick="fun()" /> ------------ </form> Then to validate the fields i have used JavaScript.They are validating rightly using a alert box. But when i am pressing ok of the alert box the control is passing to the page i have written in action of the form.I want when i will press ok it should come back to the same page.Only if all fields are then it should go to the page refereed in action. Can anyone help me? The JavaScript code is <script type="text/javascript"> function fun() { var x=document.forms["reg"]["firstname"].value; if (x==null || x=="") { alert("First name must be filled out"); } Hello, I dont know if I am going about this the right way, but.. I am trying to validate an email address. If the email is a valid looking email address, it will render the submit button disabled to prevent dupe's while the rest of the script processes. The email validation portion works, but, the part where it renders the form submit button disabled does not: <script type="text/javascript"> function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;} else {return true; submit.disabled = true;} } } function validate_form(thisform) { with (thisform) { if (validate_email(email,"Please enter a valid email address.")==false) {email.focus();return false;} } } </script> Any guidance or help would be apreciated. I keep getting validation errors for using && as and. I've read to put "&" in place of it, but whenever I do this, the code stops working. I've tried seperate parenths, and still confused. anyone help to make this work and validate at the same time? if (first=="" && last=="") first = last = "Unknown"; if (first == '') document.writeln(last); else if (last == '') document.writeln(first); else document.writeln (last + ", " + first); Dear All, I can check now a field is isNumeric via this method var isNumeric = /^[0-9.]+$/;. My problem now user can put two or more decimal and I want to limit just to single decimal and only 2 numbers before the decimal? How to edit please? For my class activity(home work) I need validate a form which has several fields. I have created the form (html) and wrote some codes for validation. I want all my form fields display help text when they get focused and when the user enter invalid data display error text(not alert). All my help text are working. but error text are not. I wrote on focus and on blur events and functions for each field. But every time I preview it on IE I am getting "object expected error" I carefully checked all the element Id and those are okay. Please help me. function myFocusHandler(e) { var newClassName; var eventTarget; if (e.target) { eventTarget = e.target; } else if (e.srcElement) { eventTarget = e.srcElement; } else { eventTarget = window.event.srcElement; } if (e.type == "focus" ) { newClassName = "helpshow"; eventTarget.className = 'inputfocus'; } else if (e.type == "blur" ) { newClassName = "helphide"; eventTarget.className = 'inputblur'; } var relatedSpansId = eventTarget.id + "help"; document.getElementById(relatedSpansId).className = newClassName; } function errorshow(elementId) { var relatedSpansId = elementId + "error"; document.getElementById(relatedSpansId).className = "errorshow"; function hideError(elementId) { var relatedSpansId= elementId + "error"; document.getElementById(relatedSpansId).className = "errorhide"; } function validateAllFields() { var isemailOK = false; var isformValid = true; var email=document.getElementById("email"); IsemailOK=IsemailValid(); if (IsemailOK == false) { formIsValid = false; errorshow("email"); } else { errorhide("email"); } return formIsValid; } function isemailValid() { var emailIsValid=false; var emailElement; var emailValue; emailElement = document.getElementById("email"); emailValue = emailElement.value; if (emaiValue== "/^[0-9A-Za-z\.\-_]+@([0-9A-Za-z\-_]+\.)+[A-Za-z]{2,}$/") { emailIsValid=true; }else{ emailIsValid=false; } return emailIsValid; function validateemail(event) { myFocusHnadler(event); var isemailOK = false; isemailOK=isemailValid(); if(emailOK == false) { errorshow("email"); }else{ erroehide("email"); } } Good Day, I am new to this forum so i hope i am posting in the correct place. I have been working on a form validation in javascript where the error messages should be displayed beside the form field (no alerts!). The error message is displayed when i iuse alerts but not otherwise. I have included a code snippet below. Any help will be greatly appreciated. Thanks in advance. function validation() { //alert('made it here'); var fName = document.getElementById('txtFname').value; var fNameId = document.getElementById('txtFname'); if(validateName(fName,fNameId)){ return true; } return false; } function validateName(name,id){ var ck_name = /^[A-Za-z0-9 ]{6,20}$/; //alert('made it it here'); if(!ck_name.test(name)) { //alert("Invalid"); var message = "Should be between 3 and 20 characters and made up of etters, numbers or - symbol"; //create a new span element var sp = document.createElement('span'); //assign the new span element a class sp.className = 'error'; //assign span some content sp.appendChild(document.createTextNode(message)); //place the message after the form field document.body.insertBefore(sp, id); name.value=""; name.focus(); return false; } return true; } Hello there. I am trying to validate data for text boxes, radios and check-boxes which are stored in an object. Can anyone suggest how I might go about doing so? Maybe there is a website to learn from? I've had a good look around myself but haven't come across what I'm looking for unfortunately. Thank-you. I AM TRYING TO VALIDATE THE AGE RANGE SO THAT IT CAN ACCEPT AN AGE BETWEEN 16 - 99 BUT SOME HOW IM NOT GETTING THROUGH CAN ANYONE HELP ME WITH THAT PLEASE THANKS IN ADVANCE Code: <html> <head> <title>Registration</title> <script type="text/javascript"> function validation(form) { var invalid =" "; var minlength = 6; var emailchar =/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var numchar =/(^\d+$)|(^\d+\.\d+$)/; var userName = registration.u_name.value; var firstName = registration.f_name.value; var lastName = registration.l_name.value; var yourage = registration.age.value; var pw1 = registration.pwd.value; var pw2 = registration.pwd1.value; var em_adss = registration.e_address.value; if (userName.length ==""){ alert("Please enter your USERNAME."); return false; } if ((userName.length < 5) || (userName.length > 15)) { alert("User name must be between 5 and 15 characters"); return false; } if (firstName.length ==""){ alert("Please enter your FIRSTNAME."); return false; } if (lastName.length ==""){ alert("Please enter your LASTNAME."); return false; } if (yourage.length ==""){ alert("Please enter your AGE."); return false; } if (! registration.age.value.match(numchar)){ alert ("Please enter a valid age."); return false; } if ((age < 16) && (age >99)){ alert ("Please enter and valid age range"); return false; } if (pw1 == '' || pw2==''){ alert ("Please enter password twice"); return false; } if (registration.pwd.value.length < minlength){ alert ("Your password must be at least" + minlength + "characters in length."); return false; } if (registration.pwd.value.indexOf (invalid) > -1) { alert("Spaces are not allowed in the password"); return false; } if (pw1 != pw2) { alert ("Your passwords didn't match. Please re-enter"); return false; } if (em_adss.length ==""){ alert("Please enter your EMAIL."); return false; } if (! registration.e_address.value.match(emailchar)){ alert("Stop playing games.\n Please enter a valid email address"); return false; } return true; } </script> </head> <body> <form name="registration" action="response.html" method="get" onSubmit="return validation(this);"> USERNAME:<br> Between 5-15 characters. <input name="u_name" type="text" size="35" maxlength="50"> <br><br> FIRSTNAME: <br> Enter your first name. <input name="f_name" type="text" size="35" maxlength="50"> <br><br> LASTNAME: <br> Enter your last name. <input name="l_name" type="text" size="35" maxlength="50"> <br><br> AGE: <br> Enter your age. (16-99) <input name="age" type="text" size="35" maxlength="50"> <br><br> PASSWORD: <br> Enter your password. <input name="pwd" type="password" size="35" maxlength="50"> <br><br> VERIFY PASSWORD: <br> Verify your password. <input name="pwd1" type="password" size="35" maxlength="50"> <br><br> EMAIL: <br> Enter your email address. <input name="e_address" type="text" size="35" maxlength="50"> <br><br> <input type="submit" value="Submit Information" name="submit"> <input name="reset" type="reset" value="Reset Information"> </form> </body> </html> Hi all, I am trying to get a form to validate when the submit button is clicked. If I use this method with an <input type="submit"> it works fine, the validation runs and if there are no errors, the form submits: Code: <form name="form" class="form" id="Form" method="post" action="contact/send_email.php" onsubmit="return validate.check(this); "> <label for="Full_Name" accesskey="U">Your Name <span>*</span></label> <input name="Full_Name" type="text" id="Full_Name" /> <label for="Email_Address" accesskey="E">Email <span>*</span></label <input name="Email_Address" type="text" id="Email_Address" /> <label for="Telephone_Number" accesskey="P">Phone <span>*</span></label> <input name="Telephone_Number" type="text" id="Telephone_Number" /> <label for="Your_Message" accesskey="C">Message <span>*</span></label> <textarea name="Your_Message" id="Your_Message"></textarea> <input name="contactus" type="submit" class="submitbutton" id="contactus" value="Send Email" /> <p class="required"><span>*</span><i> denotes required fields.</i></p> </form> However, if i try to use a link to submit the form,the validation will not run: Code: <form name="form" class="form" id="Form" method="post" action="contact/send_email.php" onsubmit="return validate.check(this); "> <label for="Full_Name" accesskey="U">Your Name <span>*</span></label> <input name="Full_Name" type="text" id="Full_Name" /> <label for="Email_Address" accesskey="E">Email <span>*</span></label <input name="Email_Address" type="text" id="Email_Address" /> <label for="Telephone_Number" accesskey="P">Phone <span>*</span></label> <input name="Telephone_Number" type="text" id="Telephone_Number" /> <label for="Your_Message" accesskey="C">Message <span>*</span></label> <textarea name="Your_Message" id="Your_Message"></textarea> <div class="btns"><a href="#" class="button1" onclick="document.form.submit();return false;">Send Email</a></div> <p class="required"><span>*</span><i> denotes required fields.</i></p> </form> I'm very new to js so any help would be greatly appreciated. Thanks Chris |