JavaScript - Two Way Server/client Communication Paradigm
Ok, so I consider myself to be fairly proficient with programming in general, although I am admittedly new to bi-directional networking. So here I am asking about methodological approaches.
A non-disclosure clause prevents me from giving any details, but I don't think they would actually be pertinent. What is important is that the system must accept input from client side Javascript from many users and disseminate that input (once processed) to a number of users. In a way, think multi-channel chat system (totally different environment, but the mechanisms seem similar). As I see it, I have two options: periodic server polling, or server-sent events (compatibility with IE is not a requisite). So, my question is, which method (of these two or even something that I am not thinking of) is superior from the standpoint of server bandwidth? Periodic server polling obviously seems as if it would send a great many unneeded requests, but my hesitation for dismissing this method is that I don't see any client being idle for any considerable length of time (thus the client will send commands to the server quite often) and it simplifies my server software by delegating that section of logic (which data chunks need to be updated) to client CPU's. Additionally, I can throttle the update period based on server load. Server-sent events initially sounded like a great idea until I thought about the extreme likelihood of a large number of users (upwards of a hundred) interaction with the same chunk of data, thus requiring that each client receive an update every time another client does anything, which is likely once ever second or two, thus resulting in hundreds of updates being sent to hundreds of clients every second. Sounds similar to a denial of service situation to me. Anyway, I think I already know what I'm going to do for this project, but thought that this might be a good way to introduce myself to these forums. Similar TutorialsHi, I am trying to follow this tutorial and make a login feature for my apphttp://code.google.com/webtoolkit/do...unication.html to use GWT's remote procedure calls (RPC) to have server client communication to eventually make a web app that talks to a database. I thought I followed it exactly but when the async returns it fails and returns an exception: "com.google.gwt.user.client.rpc.InvocationException" Can someone please take a look at the client code, it must be something stupid that I am doing wrong. Thanks Here's the code: In the calling client class: Code: private MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class); ((ServiceDefTarget)svc).setServiceEntryPoint(GWT.getModuleBaseURL()); //loginButtonListener btnDBLogin.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { svc.checkLogin(txtUsername.getText(),txtPassword.getText(), new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { if (result.booleanValue() == true) { System.out.println("Works"); } else { System.out.println("Invalid UserName or Password"); } } public void onFailure(Throwable ex) { System.out.println("FAILU " + ex.toString()); } });//end checkLogin }//end onCLICK });//endbtnlistener MyService.java (client interface) Code: package com.rob.projects.client; import com.google.gwt.user.client.rpc.RemoteService; public interface MyService extends RemoteService { public Boolean checkLogin(String userName, String password); } MyServiceImpl.java (server code) Code: package com.rob.projects.server; import com.rob.projects.client.MyService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class MyServiceImpl extends RemoteServiceServlet implements MyService { private static final long serialVersionUID = 1L; public Boolean checkLogin(String userName, String password) { System.out.println(userName); if (userName.equalsIgnoreCase("bingo")) { // Check the database return true; } else return false; } } web.xml (to specify where the servlet is) PHP Code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- <servlet> path='MyService'class='com.rob.projects.server.MyServiceImpl' </servlet> --> <!-- Servlets --> <servlet> <servlet-name>MyServiceImpl</servlet-name> <servlet-class>com.rob.projects.server.MyServiceImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServiceImpl</servlet-name> <url-pattern>/satapp</url-pattern> </servlet-mapping> <!-- Default page to serve --> <welcome-file-list> <welcome-file>SATapp.html</welcome-file> </welcome-file-list> </web-app> I have heard that it is wrong to just do client validtion. SO can anyone help me with my form? The code below, has client validation and php and I am not sure that I have got it right. Also I would need to cover server side validation too but have no idea on how to do this. I must say I have very small knowledge of JS. Does anyone know the easiest method of doing forms with php, JS server and client side validation. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta content="en" name="language" /> <meta content="Seniors community venue contact details, Seniors community venue contact form, email, address, and telephone number" name="description" /> <meta content="Seniors community venue contact form, email, telephone, address" name="keywords" /> <title>Seniors Community Venue - Contact details</title> <link href="../styles/mainstyle.css" rel="stylesheet" type="text/css" /> <link href="../styles/navigation.css" rel="stylesheet" type="text/css" /> <link href="../styles/layout.css" rel="stylesheet" type="text/css" /> <link href="http://fonts.googleapis.com/css?family=Cabin|Ubuntu" rel="stylesheet" type="text/css" /> <link href="../styles/form.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../javascript/validate.js"></script> <style type="text/css"> .antispam { display: none; } </style> <script type="text/javascript"> var first = "enquiries"; var last = "seniors260.org";</script> </head> <body> <div id="bodyblock"> <div id="container"> <div id="header"> <div class="indentmenu"> <ul> <li><a href="faqs.html">FAQS</a></li> <li><a href="venue_location.html">Location</a></li> <li><a href="about_us.html">About Us</a></li> <li class="first"><a href="home.html">Home</a></li> </ul> </div> <div class="logo_venue"> <img alt="Seniors Community Venue logo" height="100" src="../images/venue_logo.gif" width="200" title="Return to hompage" /></div> <div class="top2"> <p class="tagtitle">"The best community venue<br /> your money can buy"</p> <address class="top"> 260 Stanstead Road<br /> London SE23 1DD<br /> 020 8699 4977</address> </div></div> <div class="indentmenu2"> <ul> <li><a href="room_hire.html">Room Hire</a></li> <li><a href="testimonials.html">Testimonials</a></li> <li><a href="album.html">Photo Album</a></li> <li class="first2"><a href="venue_donations.html">Donations</a></li> </ul> </div> <div id="content"> <h1>Venue Contact Details</h1> <h2>Contact Form</h2> <div id="form_box"> <form id="form" action="../php_files/submit2.php" onsubmit="return validate()" enctype="multipart/form-data" method="post" name="form_to_email" /> <fieldset> <legend>Contact Form</legend> <p><label for="name"><span>Name</span></label><input id="name" name="name" size="35" type="text" /></p> <p><label for="email"><span>Email</span></label><input id="email" name="email" size="35" type="text" /></p> <p><label for="subject"><span>Subject</span></label><input id="subject" name="subject" size="35" type="text" /></p> <p class="antispam">Leave this empty: <br /> <input name="url" /></p> </fieldset><fieldset> <legend>Message</legend> <textarea id="message" cols="50" name="message" rows="10"></textarea></fieldset><fieldset> All fields Required </fieldset><p> <input id="submit" name="submit" type="submit" value="Submit" /></p> I know that Javascript is client side, but I'd like to know the best way to populate HTML drop downs in real time based on information typed in the other HTML form fields with information found on the server as opposed to the client. For instance if a user wants to select certain files located in a directory on the server, as they type in the pathname supposedly containing the files the drop downs continually refresh themselves with the server files listed in that directory (if it exists, and apache has permissions to see what's inside) as if it was showing client files instead. What would be nice is if my browser could continually query the server for some of its private information and not have to refresh itself to obtain it, whether that means the server-side would have to continually refresh itself makes no difference to me as long as the client-side doesn't have to. But I guess this is not possible because no matter what you would have to at least refresh the client-side page once? Submitting the form to a CGI or PHP script would not work because I need this functionality to help populate the form BEFORE I send it. I would like to not have to press a button to update the form every time I change the pathname and need to update the drop downs since this would be annoying. I'm open to anything that could do this or something similar not just Javascript. I'm not sure if you could accomplish this by converting the HTML page to CGI/PHP and having it continually reload itself without refreshing the page? I'm not worried about any security risks this may pose because: 1) The server is located on company intranet which is firewalled 2) I could always password protect and encrypt all transmissions, making sure only authorized users use the app Hi people, I need help as follows: On the server side I have a php generated session parameter. I need to pass it to javascript on the client side page. I saw on the web the following solution: <script language="JavaScript"> var mySessionVar="<%= Session["MySessionVar"] %>"; </script> I tried it but it did not work. I could not find any explanation of this syntax - will appreciate one. Any suggestions, maybe in another way? Thanks I have written code for two function. One takes two strings and puts them into an array. The other function takes that array and generates buttons to be written into a different iFrame. The way the page is set up is the main page, name="contentFrame" and name="buttonFrame" Below is what I have written. So far in IE (note: must use IE, no FF) I have managed to get my function to refresh the frame that it's being called in, but NOT the other frame (buttonFrame) That's what I need to do, as can be deduced from the code. Lastly, let me ammend this post by saying that I'm a PHP coder, not a JS coder, so bear with me I'm still learning JS. Code: // Declaring vars!! yahoo! // Set cmdKey counter (so we know which order we load our values in...) var cmdCtr = 0; // Define our array that will hold the various keycodes for the buttons var cmdKeyCode = new array; // Define our array that will hold the keytexts var cmdKeyText = new array; // To grab button ID's and Values on the fly from the JIT... function addCmd(Text, keyCode) { cmdKeyCode[cmdCtr] = keyCode; cmdKeyText[cmdCtr] = Text; cmdCtr++; } // Function for creating an html string from arrays, // refresh button frame and then write buttons to frame. // THIS FUNCTION IS EXECUTED FROM THE CONTENT FRAME - writes to buttonFrame function writeCmd() { // Since this function is called immediately after the button arrays are populated.. // we need to make sure that the button frame is empty and ready to accept new buttons! // Since the button frame is a blank html doc, all we gotta do is refresh it... :) top.buttonFrame.document.reload(); // Let's make this blank page valid html... var htmlOpen = "<html><head><link rel='stylesheet' type='text/css' src='master.css' /></head><body>"; top.buttonFrame.document.write(htmlOpen); for(i=0; i < cmdCtr; i++) { var value = cmdKeyText[i]; var code = cmdKeyCode[i]; // Let's write the buttons!! top.buttonFrame.document.write("<input name='" + code + "' type='button' value='" + value + "' id='" + code + "' class='submenu_special' />"); } // Let's close our HTML in the button frame var htmlClose = "</body></html>"; top.buttonFrame.document.write(htmlClose); } // Code for hiding/showing menu items function showHide(theid){ if (document.getElementById) { var switch_id = document.getElementById(theid); if(menu_status[theid] != 'show') { switch_id.className = 'show'; menu_status[theid] = 'show'; }else{ switch_id.className = 'hide'; menu_status[theid] = 'hide'; } } } I have the following JavaScript (see below). The script requests an XML file from the server and displays it on the page. The script works fine when the requested XML file is stored on the same server as the script. The problem is when I try requesting an XML file from an external server such as the National Weather Service. I get an error. If I take the XML file from the National Weather Service and save it to my server it works. Why can't I use my script to request XML files stored on external servers? Thanks in advance for any help. Javascript Code Code: window.onload = initAll; var xhr = false; function initAll() { document.getElementById("makeTextRequest").onclick = getNewFile; document.getElementById("makeXMLRequest").onclick = getNewFile; } function getNewFile() { makeRequest(this.href); return false; } function makeRequest(url) { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (xhr) { xhr.onreadystatechange = showContents; xhr.open("GET", url, true); xhr.send(null); } else { document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest"; } } function showContents() { if (xhr.readyState == 4) { if (xhr.status == 200) { if (xhr.responseXML && xhr.responseXML.contentType=="text/xml") { var outMsg = xhr.responseXML.getElementsByTagName("choices")[0].textContent; } else { var outMsg = xhr.responseText; } } else { var outMsg = "There was a problem with the request " + xhr.status; } document.getElementById("updateArea").innerHTML = outMsg; } } HTML Code 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> <title>My First Ajax Script</title> <script type="text/javascript" src="script01.js"></script> </head> <body> <p><a id="makeXMLRequest" href="http://www.weather.gov/xml/current_obs/KOJC.xml">Request an XML file</a></p> <div id="updateArea"> </div> </body> </html> I need help to make a Server to server connection I already have a server connected to clients, clients send msgs and it echoes back to all of them and now i want when a client sends a msg it echoes on his server and the other server too .. so when any of the clients on any of the servers sends a msg it is broadcasted all over the servers to all clients This is my SERVER code Code: import java.io.*; import java.net.*; public class MultiThreadChatServer { // Declaration section: This part to declare the server socket, client // socket, input stream // and output stream static Socket clientSocket = null; static ServerSocket serverSocket = null; // server can hold up to 10 clients static clientThread t[] = new clientThread[10]; public static void main(String args[]) { int port_number = 6000; if (args.length < 1) { System.out.println("Server Started \n" + "Now using port number=" + port_number); } else { port_number = Integer.valueOf(args[0]).intValue(); } // Initialization section: Where I try to open a server socket on the // given port try { serverSocket = new ServerSocket(port_number); } catch (IOException e) { System.out.println(e); } // Create a socket object from the ServerSocket to listen and accept // connections // Open input and output streams for this socket will be created in // client's thread since every client is served by the server in // an individual thread while (true) { try { clientSocket = serverSocket.accept(); for (int i = 0; i <= 9; i++) { if (t[i] == null) { (t[i] = new clientThread(clientSocket, t)).start(); break; } } } catch (IOException e) { System.out.println(e); } } } } // This client thread opens the input and the output streams for a particular // client, // ask the client's name, informs all the clients currently connected to the // server about the fact that a new client has joined the chat room, // and as long as it receive data, echos that data back to all other clients. // When the client leaves the chat room this thread informs also all the // clients about that and terminates. class clientThread extends Thread { DataInputStream is = null; PrintStream os = null; Socket clientSocket = null; clientThread t[]; public clientThread(Socket clientSocket, clientThread[] t) { this.clientSocket = clientSocket; this.t = t; } public void run() { String line; String name; try { is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); os.println("Enter your name."); name = is.readLine(); os.println("Hello " + name + " you can now start chatting with all the connected chat-mates"); for (int i = 0; i <= 9; i++) if (t[i] != null && t[i] != this) t[i].os.println(".." + name + " has entered the chat room .."); while (true) { line = is.readLine(); if (line.startsWith("/quit")) break; for (int i = 0; i <= 9; i++) if (t[i] != null) t[i].os.println("<" + name + "> " + line); } for (int i = 0; i <= 9; i++) if (t[i] != null && t[i] != this) t[i].os.println("" + name + " has left the chat room .."); os.println("Bye " + name + " .."); // Clean up: // Set to null the current thread variable such that other client // could // be accepted by the server for (int i = 0; i <= 9; i++) if (t[i] == this) t[i] = null; // close the output stream // close the input stream // close the socket is.close(); os.close(); clientSocket.close(); } catch (IOException e) { } ; } } Hey guys. Didnt know what forum to put this in, but i figured i would put it here. Basically im making an ajax chat client. I dont know if anyone here as ever looked at googles chat client code, but if anyone knows how to make one function the same way as it, I would love if you would help me figure it out. I tried making a chat client, but it ended up being slow, buggy, and you couldnt select text because the innerhtml was refresshing so much. So how can I make a good chat client like googles? Thanks! I don't have much experience in Javascript and would like to hear your suggestions before choosing which direction to pursue for my project. I want to design a web page which allows a user to input a file which contains a list of addresses. Then send these addresses to Google Maps API for geocoding and returned XY coordinates will be saved in a file and downloaded to the PC. Can this be done completely in Javascript(client side handling) or the input addresses need to be sent to a server and let the server talk to Google Maps API to complete geocoding and then send back the coordinates data to the browser(sever side handling). Please help!
hi, how can i get client mac address OR hdd id with javascript for internet explorer? i am making a registration page for my website and for validation using javascript...is there any way to know on my client side javascript enable or not....
Hello, I have two problems. Firstly I am trying to make a form with client side validation but I have come across a problem. I need to validate the whole form under just one button but for validating email and phone number I have two different buttons and I am not sure how to make all the code run under just one button when it is submitted. The second problem is with validating the phone number. I am sure the code and javascript is fine, but for some reason it will not work. Here is my code: HTML 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"/> <script type="text/javascript" src="client_validation.js" /> </script> <link rel="stylesheet" type="text/css" href="Client validation.css" /> <title> Client Validation </title> </head> <body> <form name="contact_form" method="post" action="submit" onsubmit="return validate_form ( );"> <h3><strong>Client Validation</strong></h3> <p>Your Name: <input type="text" name="text1"></p> <p>Your Last Name: <input type="text" name="text2"></p> <p>Email: <input type="text" id="email" name="text3"></p> <p>Phone: <input type="text" name="text4"></p> <p>Address: <textarea cols="20" rows="5" name="text5"></textarea></p> <p>Do you agree to the Terms and Conditions? <input type="checkbox" name="text6" value="Yes"> Yes <p><input type="submit" name="send" value="Send Details"></p> </form> Your Email: <form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');"> <input type="text" id="email" name="email" /> <input type="submit" value="Submit" /> <form method="post" action="data.php" name="form1"> <p>Enter Number <input type="text" name="phoneNo"></p> <input type="button" name="btn1" value="submit" onClick="CheckNumber()"> </body> </html> JAVASCRIPT Code: function validate_form ( ) { valid = true; if ( document.contact_form.text1.value == "" ) { alert ( "Please fill in the 'Your First Name' box." ); valid = false; } if ( document.contact_form.text2.value == "" ) { alert ( "Please fill in the 'Your Last Name' box." ); valid = false; } if ( document.contact_form.text5.value == "" ) { alert ( "Please fill in your address." ); valid = false; } if ( document.contact_form.text6.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; } return valid; } function validate(form_id,email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.forms[form_id].elements[email].value; if(reg.test(address) == false) { alert('Invalid Email Address'); return false; } } function CheckNumber() { var PhoneNumber=document.form1.phoneNo.value; for (var i=0; i<PhoneNumber.length; i++) { var c=PhoneNumber.charAt(i); if (!(c>0 || c<9)){ alert("This is not a valid Phone Number"); break; } } } I hope you guys can help. Thank you I have been interested in APIs in the last time and i want to know exactly how it works from the server side. so i tried to figure out how the client side API working , first step i took the Google Plus One JS client side code and i tried to figure out how it works , mostly i tried to find how it gets connect to the server side. i couldn't find what this whole code doing , mainly because i focused to find Ajax requests , but there is none of them. this is the api I checked : https://apis.google.com/js/plusone.js now , my questions is simple , i want to know how API connect to the server side , do they use AJAX? what exactly they use to send request to server side ? i need you're help to know more on how api working on Client side , mainly on the connect to the server. so , how it get's done? I'm new to web programming, and so I may be going about this all wrong but this is what I'm trying to do. I'm creating an interface to access my google base, I can do that part without much trouble but to access the server you need to request a session token. This token has to be sent to the server along with your query. I use JS on the main page which calls a php script that requests the key, then calls the server for a full list of items which is then passed back to the javascript in JSON format. The user then selects a field from the option box and i need to requery the server for the updated list. But to do this i need to resend the session token, and this is where I'm having trouble. I need to save this token, but im not sure the best way to go about this. I can pass it back to the JS portion and save it as a variable that i can then pass to the PHP script that queries the server, but im worried the key may contain private information about my log in information. Is there a way to make this token variable hidden in the JS so that the client could not see it? Or am i way off base and the client can't view any of the variables anyways? If someone has a suggestion for me that would be much appreciated. Hey guys. I made a chat client today (my first one and it's pretty sweet so far) I have a speed problem though http://xonicgames.com/hudson/chat.php Once there are ~20+ posts it starts getting slow (at least on my connection) It does an ajax request every 500 seconds (dont know if that should be slowed down or not) What can I do to speed it up? Thanks Does anyone know of a photo gallery where the CLIENT is able to update both the images and the captions? Please and thank you. Or...... does anyone know of a gallery which pulls the photos and captions from a database? I can build a client interface to the database myself? Thanks again. I've been avoiding php and asp trying to do as much client-side as possible, as lightweight as possible, but don't know enough to know if I should go that route. I want to have several js/jquery games, really simple stuff like flash cards, memory games, matching, etc Currently when you do something correctly it adds 5 points like: points+=5; and if you get it wrong lose 3 points: points-=3; At the end of the game it flashes a play again button which resets points and all the cards, and that's it. So I was trying to think of ways to add a global variable that adds the latest score to it, and maybe gives you a random "prize" which would be another variable randomly selected from an array of "prizes", or better yet, "achievements"....between games....on the same domain. I'd like to eventually make something similar to a "crafting" system, where if you have 3 particular achievements you can convert them into some new achievement...I imagine just a function that checks if you have the 3 objects, then if so it adds some 4th object and removes the first 3. I was avoiding server side databases because I was avoiding authentication/user accounts for the time being...I would probably eventually like to let people play games, and if they want to save their scores long term, register an account....but if they don't want to register an account, I'd like them to have the same functionality for that session, where they can play a few games from around the site while accumulating a global score and list of achievement variables. I was messing around with jstorage, but am not sure if it will work for what I'm thinking....it only accepts strings, and I couldn't figure out how to write the variableName.toString() into the jstorage "value" of the key:value pair...it gives me the impression it's more for storing form data as a convenience to the user. So is there a client side variable storage that's simple, lightweight, and works with mobile? Or a way to write .toString() value of objects into jstorage? Or should I just break down and start investigating my server side options? Is there some middle ground where stuff can be done client side, then give the option to register to save that information long term? edit::I'm thinking of my 3 year old nieces ipad games, they're simple drag drop, highlight shapes, pattern association, etc but I want it so each time you play it remembers where you left off...basically a cookie would have been cool if it were bigger and not sent every packet....so kinda a "save-state" and "load-state" functionality.. edit2::sqlite seems like a legitimate option but then reading through it, it gets convoluted how to implement on my bluehost account... Hello, I hope someone can help. I know on the front end using js you can get the date and time on client machine and store in a hidden field so it can be grabbed to use on the back-end to store in a database or even return a special message based on their time. However, I'm not too sure how to begin. Would anyone happen to have any idea on how to do this? Thanks in advanced! I wish to change the dynamic text in a javascript to that which is in a MySQL database using PHP. this is then used in a flash scroller. currently i have hard coded the text in the javascript file. is there a way to have PHP run in the javascript file before it is sent to the endusers? or another way ? 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> |