scryoko
Nov 26 2005, 07:12 AM
Hello, I'm wondering if someone can help me with Javascript. I have created a form and the page in which the information submitted will be displayed (I will call these pages the form page and the submit page for easier reference). I want to know how to verify if a form is filled out correctly in the following manner: 1. Instead of placing the JavaScript form validation code on the form page, I want to add it on the submit page. 2. If there is an error from the filling out the form (i.e. the text field for "First Name:" was not entered), I want to display an error message on the same submit page to the user. (I want to display all error messages for every single input field that is invalid.) 3. In addition, I also want to make it so that if any of the data input was invalid, I want to provide a link to the user so he/she can click on it to return back to the form. Sure, a normal link to the forms page will solve this problem but then, I also want it so that all of the data that was already submitted needs to be re-populated in the form, except the data that was invalid (i.e. if all of the data was valid other than the first name, then when the user clicks on the link to go back to the form, all of the fields will re-populate with the data that the user had submitted -- except for the text field that is for inputting the first name.) I was given a hint to use hidden form fields to do this but I'm not sure how exactly I'm going to go about doing that.. I was able to create a code for form validation but I only know how to validate the form on the *form* page (as opposed to the *submit* page); here is my current script for the form page is the following: CODE <html> <head> <script language="JavaScript"> function validateOnSubmit() {
errorMsg = " ";
invalid = null;
firstName = document.FormPage.firstname.value.length; lastName = document.FormPage.lastname.value.length; street = document.FormPage.streetname.value.length; city1 = document.FormPage.city.value.length; zip = document.FormPage.zipcode.value.length;
if ( firstName == 0 ) { errorMsg += "-- First Name\n";
if ( invalid == null ) { invalid = document.FormPage.firstname; }
}
if ( lastName == 0 ) { errorMsg += "-- Last Name\n";
if ( invalid == null ) { invalid = document.FormPage.lastname; }
}
if ( street == 0 ) { errorMsg += "-- Street\n";
if ( invalid == null ) { invalid = document.FormPage.streetname; }
}
if ( city1 == 0 ) { errorMsg += "-- City\n";
if ( invalid == null ) { invalid = document.FormPage.city; }
}
if ( zip != 5 ) { errorMsg += "-- Zip Code\n";
if ( invalid == null ) { invalid = document.FormPage.zipcode; }
}
if ( "-" != document.FormPage.phone.value.charAt(3) || "-" != document.FormPage.phone.value.charAt(7) ) { errorMsg += "-- Phone Number\n";
if ( invalid == null ) { invalid = document.FormPage.phone; }
}
if ( " " != document.FormPage.creditcardnumber.value.charAt(4) || " " != document.FormPage.creditcardnumber.value.charAt(9)) {
if ( document.FormPage.creditcardnumber.value.charAt(14) != " " ) { errorMsg += "-- Credit Card Number\n";
if ( invalid == null ) { invalid = document.FormPage.creditcardnumber; }
}
}
if ( errorMsg == " " ) { return true; }
else { alert("The following are invalid:\n" + errorMsg); invalid.focus(); return false; }
} </script> </head> <body> <form name="FormPage" action="submit.html" method="GET" onSubmit="return validateOnSubmit();">
First Name: <input type="text" name="firstname">
/* then I have Last Name, Address, Phone Number, Credit Card Type, Credit Card Number, and the submit button as well */ </body> </html> And for the submit page, this is what I currently have: CODE <html> <head>
<!--Disclaimer: This code belongs to Fynn Consulting Ltd. --> <script language="JavaScript"> function getURLParam(strParamName) { var strReturn = ""; var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ) { var strQueryString = strHref.substr(strHref.indexOf("?")); var aQueryString = strQueryString.split("&"); for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) { if ( aQueryString[iParam].indexOf(strParamName + "=") > -1 ) { var aParam = aQueryString[iParam].split("="); strReturn = aParam[1]; break; }
}
}
return strReturn; } </script> </head> <body>
First Name:
<script language="javascript"> document.write(getURLParam('firstname')); </script>
/* I also have the rest of the data displayed in this manner */
</body> </html> I have tried to simply copy and paste the script in the form page onto the script in the <head> tag of the submit page and then deleting the alert (so that there is no pop-up window) and then in every if statement (for if there is an field that is invalid), I will display a code like below: CODE if ( firstName == 0 ) { document.write("First Name is invalid.\n"); } However, after changing the code to this, when the data gets passed over to the submit page (and is, therefore, supposed to be validated on the submit page), nothing seems to get validated because even if there is supposed to be an invalid entry, no error message is displayed. I think this may have to do with the fact that I need to call the function in the body of the submit page, but I do not know how to do that without using the <form> tag. So... is there any other way to call a javascript function in the <head> tag from the <body> tag other than using the <form> tag such as: CODE <form name="FormPage" action="submit.html" method="GET" onSubmit="return validateOnSubmit();"> Um... I also have two more questions... 1. How do I go about validating radio buttons? As in, check to see if the user had clicked on any of the buttons -- if they didn't check any of hte given choices, then display an error message (in alert format)? 2. How do I make it so that whitespace characters are not valid entries into any of the fields? If there is anything in here that is not clear, please ask and I will try my best to explain it once more. Thank you to anyone who is able to help me. I really appreciate it a lot. -- scryoko
Reply
hbs_25
Jan 12 2006, 12:38 PM
Man!!! What a huge question... ok, let's go! First of all, you don't need to copy and paste the code in the form to the submit page. You'll just need to alter your code to this and put beloow the <body> tag CODE <script> if ( getURLParam('firstname').length == 0 ) { document.write("First Name is invalid.\n"); } </script> ... and don't forget! Remove the onSubmit action from the form tag CODE <form name="FormPage" action="submit.htm" method="GET"> ... and the other questions: 1 -Validating radio buttons? Try this CODE <html> </head> <script> function check(){ if(document.form1.radiobutton[0].checked){ alert('yes');} else{alert('no');} if(document.form1.radiobutton[1].checked){ alert('yes');} else{alert('no');} } </script> <body> <form name="form1" method="post" action=""> <input name="radiobutton" type="radio" value="1"> <input name="radiobutton" type="radio" value="2"> <input type="button" name="Button" value="Button" onClick="check();"> </form> </body> </html> Remember that radiobuttons need to have the same name and only have the number between "[]" to make the diference. 2 - Whitespace characters are not valid entries into any of the fields? CODE if(document.form1.textfield.value==" "){alert('whitespaces!');} But this will only work if in the field have only one whitespace. To alert about the first character is white, try this CODE if(document.form1.textfield.value.substr(0,1)==" "){alert('whitespaces!');} Replace the names, make some copies and have fun! By the way, if you have some doubt, just ask me!
Reply
Jack Cheng
Mar 1 2006, 12:55 AM
First, I would recommend that you use just one page. This reduces another unnecessary page reload, resulting a much faster feedback to the users and increasing the overall performance of the site. In addition, having another page with a link to go back go fix just one error seems like a really redudant process, especially when the user continually makes errors. Having one page would really fix that. To insert error messages into the HTML, you can use <div> with an ID and reference it with document.getElementByID[whatever_id_was_in_div] and set the innerHTML property to whatever error message you want. Also, for this solution, you don't have to worry about maintaining what the user typed into the fields (not that you really have to since most browsers does it automatically...but notice the keyword most). However, if you are really set for your solution. Here are my recommendations: To maintain the user inputs, you will have to rely to saving those information in the URL (hopefully all the information in the form are not confidential). In the links to return to the form, add in the whatever users inputs you want to keep manually to the URL for the link. You can probably write a functiont to do this (in fact, probably shoud) so that it is not as redundant for all the input fields. In the form page, extract that information as you would in the submit page and add that information to the input fields. QUOTE CODE <html> </head> <script> function check(){ if(document.form1.radiobutton[0].checked){ alert('yes');} else{alert('no');} if(document.form1.radiobutton[1].checked){ alert('yes');} else{alert('no');} } </script> <body> <form name="form1" method="post" action=""> <input name="radiobutton" type="radio" value="1"> <input name="radiobutton" type="radio" value="2"> <input type="button" name="Button" value="Button" onClick="check();"> </form> </body> </html> This method is okay is you know beforehand how many radio buttons there are. However, it is definitely not suitable for a generic validation, nor very easy to maintain. There is a simpler way to check radio buttons with a loop. CODE <script> function check(){ var radChecked = false; for (i=0; i<document.form1.radiobutton.length; i++) { if (document.form1.radiobutton[i].checked) { radChecked = true; break; } } if (radChecked) { alert("good"); } else { alert("bad"); } }
This basically loops through all radio buttons with the name of radiobutton and checks if it's checked. If so, it sets the radChecked variable to true (for use in the conditional statements later) and breaks out of the loop. After the loop, a conditional statement is used to check whether the loop went through with or without finind a checked radio button. QUOTE 2 - Whitespace characters are not valid entries into any of the fields? CODE if(document.form1.textfield.value==" "){alert('whitespaces!');} But this will only work if in the field have only one whitespace. To alert about the first character is white, try this CODE if(document.form1.textfield.value.substr(0,1)==" "){alert('whitespaces!');} Again, these methods are okay. The first works, as mentioned only when there is one space. The second one, however, only checks the first character. What if the user enters something preceded by a space. The form would issue an error, but the user would not know what is wrong because the preceding space is so unnoticeable. A better solution to this problem would be set make a custom trim() function that trims all preceding and trailing whitespace characters. If the length of the string become zero after the trimming, it means that all the characters in the input field are whitespace characters. Just do a search for a trim() algorithm on google or some other search engine (it is actually very simple, but I just do not feel like opening up notepad and write the script and test it, besides, the codes published online are probably more reliable - they've probably been thoroughly tested first). Hope this helps!
Reply
Recent Queries:--
javascript form validation using layers - 1.72 hr back. (1)
-
form validation all fields js code - 11.76 hr back. (1)
-
javascript form validation innerhtml - 34.04 hr back. (1)
-
email id validation in javascript to porn - 59.08 hr back. (1)
-
character validation form in javascript using document.forms[].getelementsbytagname() - 80.62 hr back. (2)
-
how to make javascript form validation statements pop up in main body of web page - 83.04 hr back. (1)
-
inline html form validation javascript - 95.17 hr back. (1)
-
special character validation text field javascript except space / $ & - 95.89 hr back. (1)
-
javascript loop validation form - 103.94 hr back. (1)
-
how to write validation using javascript externally - 105.04 hr back. (3)
-
validation for special characters and white space on textbox js - 123.43 hr back. (2)
-
i want to validate more than one function in javascript with help of html - 130.03 hr back. (1)
-
javascript redirection in form validation - 139.55 hr back. (1)
-
javascript form validation external file - 145.92 hr back. (1)
Similar Topics
Keywords : javascript, form, validation
- 12 Javascript Image Galleries
(0)
Javascript Changes Aren't Working.
(6) The link is where I got it from, the code is my attempt at changing it, which has the identical
javascript, but it doesn't work. Can anyone fix it for me?
http://code.google.com/edu/client/samples/dhtmltest.html CODE example body {font: 14px
arial; color: #000066;} #mytext {position: absolute; top: 100px; left: 400px; font: 24px arial;
font-weight: 900; } var texttop = 100; var textleft = 400; function vanish(flag) { var myObj
= new getObj('myText'); myObj.style.visibility = (flag) ? 'hidden' :
'visible' } function m....
Javascript Help Needed : Alert(z) Works Fine But Document.write Not
please (2) hi all, I am facing problem in my javascript, any kind of help would be apreciated CODE
function basicFiles(){ //var Z = ""; for (i = 0; i var x =
document.Form.regionlist.options .value; var y = document.Form.regionlist.options
.text; var Z = "regions" + " " + " = " + y + ", "; alert(Z);
} } this works well but the following returns only errors CODE
function basicFiles(){ //var Z = ""; for (i = 0; i var x =
document.Form.....
Fun With Javascript And Forms
Lets have some fun with javascript! (2) I will post here every week with new and exciting things to do in javascript! After i finish 10 of
them , ill do Ajax(real-time) - 1.Alerting and documenting Forms Ever seen those dynamic sites
where if you hove your mouse or type something bad..etc , it popups up or dynamically gets written
onto the page? Well i am here to teach or rather help with all that stuff! Step 1:Get notepad out
and make a form CODE Text displays here: Step 2: Add the javascript Bit CODE
function onKeyDown() { document.GetElementById('r').innerHTML=document.....
Include Function For Javascript
(7) I've been working on an include function for javascript. It works just fine in Firefox and IE,
but for some reason, it doesn't result in the loading of the scripts for Safari. The code is as
follows: CODE function include(url) { // Include Guard var scripts =
document.getElementsByTagName("script"); for (var index = 0; index if (scripts.src == url) {
return; } } // Inclusion var head =
document.getElementsByTagName("head").item(0); var script =
head.appendChild(document.createElement("script")); script.type = "text/javascrip....
Problem With Javascript Alert();
(9) Hi Everyone, i just need to know that this javascript code is formatted correctly: (A piece of
code that it's written BESIDE an HTML code.) CODE My body contents |||Always keeps
telling me that this was incorrect. ....
Javascript: How Do I Create Embedded Pop-up Windows?
(7) The post title summarises my query - how do I create pop-up windows that are embedded inside a page?
Broadly, there are two kinds of JavaScript pop-ups.. one is that ultra annoying one, which pops
out a new instance of a browser window and displays something there (usually an ad) - made infamous
by all the warez and porn sites. Second one, which has come to be quite well-known of late is the
kind you see in recent versions of WordPress (in the Visual Editor) as well as LightBox based
galleries. Here a small window (or rather a div) pops-up embedded in the middle of t....
Javascript Question
Vertical Scroll Box (4) Alright well I've been working and modifying this template for about a year now I think and
I've started used JavaScript in it (bad to use templates I know, but I can't design them
x_x). So I'm trying to put a vertical scroll box in my side events panel to save space, but it
won't recognize the script. It takes the horizontal one I have as you can see if you look at
the site, but not the vertical. Actually it won't take anything in that little panel. So my
question really is, what could cause a javascript code to not work on a certain webpage ....
Add Text To Textarea
I suppose it uses DOM and JavaScript?? (6) I am working on a web "application" thing that allows you to click a button to add text to a
textarea. Similar to this forum when you click the BOLD button and it puts in {b}{/b} with the
square brackets. I want a similar function like that. Also, I want it to add wherever the cursor is,
not at the end. And after adding the thing, the cursor should be in between the tag or whatever that
was added. All the extra stuff are extra priorities. For now I would like to get something that
inserts text on click. The thing I came up with is: HTML html > head > text/javasc....
Problems With Dynamically Loading Javascript
As well as dynamically inserting HTML (2) Hello, I have started to try to create a JavaScript application (or rather, AJAX, but the
JavaScript is the part I'm having trouble with). I have come across a roadblock, though. I try
to load an external JavaScript file by editing the innerHTML of a div tag to contain <script
src="URL" type="text/javascript"> (with a real URL). The problem is that it is not loading. I have
used FireBug to check the dynamic HTML status, I get the following (with code removed): CODE
<script type="text/javascript"> <script src="source/main_login.js" typ....
I Need Help With Javascript.
help plz (7) Well, I want to learn to code in JavaScript, but when I try to view the page in Firefox, it
dosen't work. Can anyone tell me why its not working? Do i need to use a different browser?....
JavaScript Off Redirect Script
How to redirect a browser when Javascrip (2) Hi, here's a trick that will redirect a browser when JavaScript is turned off. Why not redirect
the ones that have JavaScript? It's because less than 10% of browsers have JavaScript turned
off; therefore, is better to redirect less than 10% of visitors than over 90%. Simply paste this
code into the HEAD section of your HTML document. CODE /* Created by: Will Bontrager ::
http://www.willmaster.com/ */ //--> Best regards,....
JavaScript Frames & Querystring
(4) Hi, I actually want to create a HTML page which has the capablity of reading a QueryString
(x.html?querystring=test) and then using a hidden frame pass on the data to an ASP Script on another
server. For obtaining the QueryString i use the following:- CODE function
getQueryVariable(variable) { var query = window.location.search.substring(1); var vars =
query.split("&"); for (var i=0;i var pair = vars .split("="); if (pair == variable) {
return pair ; } } } alert( getQueryVariable("QueryString") ); Now my
problem is to cre....
Vertical Marquee Using JavaScript
by The JavaScript Source (0) Hi, i find this script and hope that will be useful for somebody. Text scrolls from bottom to top,
pauses, then scrolls up and out of view. A link can be added, opening in a new window. Configuration
is simple. First copy the following code in a new file and name it vertical.js CODE /* This
script and many more are available free online at The JavaScript Source ::
http://javascript.internet.com Created by: Mike Hudson :: http://www.afrozeus.com */ /* To change
the values in the setupLinks function below. You will notice there are two arrays for each of Titles
and L....
Create And Import JavaScript Modules For A Large Script
(2) I have one main script which defines an object. I then have several other script files that define
functions for that object. I have tried using the following setup to import the functions: HTML
code snippet: Javascript code snippet: import Object.functionName; This works fine for
Mozilla Firefox, but causes an error in Internet Explorer which causes the object to be undefined.
I would like to know how better to import the functions into the main javascript (preferably without
needing to add the module script to the html file) that works in both Firefox a....
Ever Needs To Find Out A Table Height Or With With JavaScript
Well stop looking, here is the answer (CSS and JS) (2) Welcome everybody to this litle tutorial. by v.DragonEyE.n09 Introduction: Using
javascript you can find the height and width of a table, cell, div, image, etc.. the more simple way
is to ask for this... QUOTE id= "myElement" border= "0" cellpadding=
"0" cellspacing= "0" style= " height : 300px ; width
: 450px ; " > some
fake text and images for the example some fak....
JavaScript: Hide And Show Any Element With CSS
From the simple way to the more advanced way (Javascript & CSS) (6) Welcome everyone, this is my first post. The first thing you need to know is... CSS
has two special attributes, the first one is " display " and the second is " visibility ". The
difference between these two goes like this. " display ": has many properties or values, but the
ones we need are "none" and "block". "none" is like a hide value, and "block" is like show. If you
use the "none" value you will totally hide what ever html tag you have applied this css style. If
you use "block" you will see the html tag and it's content. very simple. " visibi....
Javascript: Browser Detection Script
Detect your visitors browser (0) If you want to detect your visitors browser, sebd them a message and redirect them use this script:
CODE var browserName=navigator.appName; if (browserName=="Netscape") { alert("Hi Netscape
user!") window.location = "netscape.html" } else { if (browserName=="Microsoft Internet
Explorer") { alert("Hi Microsoft Internet Exlorer User!"); window.location = "MIE.html" }
else { alert("What are you browsing with?"); window.location = "unkown.html" } } //-->
....
Calling Of Functions Between Mulitple External Javascript Files
How do I use an external script to call a function from another script (2) I have a page that requires many Javascript functions. In order to make the coding easier to read
and edit, I decided to seperate them into 3 Javascript files. Two files will each do a specific job.
One file will have the shared functions that both other 2 files will need to use. They are all
linked to a page using three tags. The difficult part is that after the page calls a function in
one of the special code files, that Javascript file will need to call the functions located in the
common Javascript file. The file will call several functions, and it will an argumen....
JavaScript: Simple Dropdown Menu
Simple Dropdown Menu (1) This simple dropdown menu is flexible enough to be used in various ways. It can be placed and
modified in the webpage as is.....
Javascript: Simple Slidedown Menu
Simple Slidedown Menu (2) This is a simple slidedown from the top menu. It can be placed on the Webpage as is. To modify it
to a slideout menu, simply change the style and postion of the menu.....
Downloads With Javascript?
(7) Hi! I want to let people download .mp3's. But i don't want them tio have to right-click and
"Save as". Is there a way with Java Script? Cheers!' Jens....
Dynamicdrive: Good Site For JavaScript Codes
(5) If anyone needs Javascript codes or similar items for their web page a great place to go is
http://www.dynamicdrive.com . They have hundreds of codes that are good. I would reccomend them for
all your javascript needs.....
Unobtrusive Javascript Image Rollovers
really cool & useful.. (0) i find this really cool..gr8 piece of code. image rollovers Create image rollovers for your
navigation without hardcoding any JavaScript into the HTML code on your Web pages. Easy to
implement, even for beginners, and works across all browsers. Degrades nicely for visitors with
JavaScript turned off. CODE img {border: none;} ul {list-style-type:none;} ul li
{display:inline;} function isDefined(property) { return (typeof property !=
'undefined'); } var rolloverInitialized = false; function rolloverInit() { if
(!rolloverInitialized && isDe....
Javascript: Text To Texbox And Back To Text
(2) i need some help i want to create a thing where when some one double clicks a certain text it
changes into a texbox where they can edit the text and the they double click and it changes into the
test they just typed in. I have found this function in javascript that does some of it but i needs
to be simplified CODE "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Span to
Text Box - Demo - DOM /* © John Davenport Scheuer */ function exchange(el){ var
nodeI=el.parentNode, inputC=document.createElement('input'), text=el.innerHTML; el.style.f....
Best Way To Learn Javascript
I would very much like to know. (9) Well, I know HTML, I know CSS, so the next step is learning Javascript. I have heard that it is sort
of an easier way to do things than PHP, though I would very much like to learn PHP as well. So, I
thought that if I learnt Javascript, I might find it easier to learn PHP when I get to that point.
The problem though is actually finding out the best way to learn Javascript. I have been to
websites and things, but every time I read through the tutorials and articles and things, I
didn't learn anything. It when in one ear and out the other, you could say. So, that is wh....
Javascript: Disable Mouse Right-click In Browser
(16) just copy and paste this on to your html site in the head tag CODE /* */ var message="Hey
YOU!\nStop Stealing my pictures or\nFACE THE PUNISHMENT!" function click(e) { if (document.all)
{ if (event.button == 2) { alert(message); return false; } } if (document.layers) { if (e.which ==
3) { alert(message); return false; } } } if (document.layers) {
document.captureEvents(Event.MOUSEDOWN); } document.onmousedown=click; // --> ....
javascript vs java
(12) in my opinion javascript is better then java becasue java requires more programing experecense
then javascript and i think to that javascript is more reliable then java in some ways....
How To Create A Popup Window With Javascript?
(19) Please help me! I want to in popup massage suggest to visitors of my site to make my site their home
page . Please note that I have some script code that visitors most click on a text to make my site
their home page . Every one that can help me please send an email to soleimanian@noavar.com....
Getting Screen Resolution using Javascript.
(8) Is it possible to get the screen resolution of the users moniter using only javascript. No other
external stuff, just pure javascript. I guess most of the people using JAVA for this. I also got
some scripts regarding this which used SCREEN.WIDTH function or something, but they did not seem to
work out. Any possible solutions. BTW, is it possible to get the resolution using PHP ( I guess it
is not ) .......
Looking for javascript, form, validation
|
*SIMILAR VIDEOS*
Searching Video's for javascript, form, validation
|
advertisement
|
|