JavaScript form validation - please help

Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
Reply

Join Date: Nov 2007
Posts: 8
Reputation: Gia is an unknown quantity at this point 
Solved Threads: 0
Gia's Avatar
Gia Gia is offline Offline
Newbie Poster

JavaScript form validation - please help

 
0
  #1
Apr 6th, 2008
Hello. I am new to JavaScript and need to make sure that all of the fields in this form are populated before the submission will go through, otherwise a message needs to popup saying which fields are missing information. Can someone please help. My code so far is:
  1. <html>
  2. <head>
  3.  
  4. <title>Gia's Web Page</title>
  5.  
  6. <link type="text/css" rel="stylesheet" href="style3.css" >
  7.  
  8. </head>
  9.  
  10. <body>
  11.  
  12. <!-- Comment: Introduction -->
  13.  
  14. <a name="introduction"></a>
  15.  
  16. <h1>This is my <b>Individual Programming Assignment #1</b>.</h1>
  17.  
  18. <br><br>
  19.  
  20. <!-- Comment: Purpose -->
  21.  
  22. <h3><i>This page has been developed by Gia.</i></h3>
  23.  
  24. <br><br>
  25.  
  26. <img src="tulip.jpg" style="opacity:0.4;filter:alpha(opacity=40)"
  27. onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
  28. onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" /><img src="tulip2.jpg" style="opacity:0.4;filter:alpha(opacity=40)"
  29. onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
  30. onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />
  31.  
  32.  
  33. <br><br>
  34.  
  35. <span id="spnWelcome"></span>
  36.  
  37. <body onLoad="greetUser()">
  38.  
  39. <script type="text/javascript">
  40.  
  41. function greetUser()
  42. {
  43. // Prompt the user for their name
  44. var usersName = prompt("Hi. What is your name?", "");
  45.  
  46. // Get an object reference to the <span> tag
  47. var welcomeTag = document.getElementById("spnWelcome");
  48.  
  49. // Create an array to hold month names
  50. var monthNames = new Array();
  51.  
  52. // Populate array with month names
  53. monthNames[0] = 'January';
  54. monthNames[1] = 'February';
  55. monthNames[2] = 'March';
  56. monthNames[3] = 'April';
  57. monthNames[4] = 'May';
  58. monthNames[5] = 'June';
  59. monthNames[6] = 'July';
  60. monthNames[7] = 'August';
  61. monthNames[8] = 'September';
  62. monthNames[9] = 'October';
  63. monthNames[10] = 'November';
  64. monthNames[11] = 'December';
  65.  
  66. // Get current date/time
  67. var today = new Date();
  68.  
  69. // Get the month number. Notice that this time, I am not adding 1 to the month number, since having a zero base monthNames array works
  70. // out perfectly with the fact that getMonth() returns a 0-based month index.
  71. month = today.getMonth();
  72.  
  73. // Get the day of the month
  74. var day = today.getDate();
  75.  
  76. // Get the full year
  77. var year = today.getFullYear();
  78.  
  79. // Format the date in the following format: MonthName day, year
  80. var formattedDate = monthNames[month] + ' ' + day + ', ' + year;
  81.  
  82. // Replace the content of the <span> tag with a personalized message
  83. welcomeTag.innerHTML = 'Hi ' + usersName + '!!! Welcome to my Website! <br>Today is: ' + formattedDate;
  84. }
  85.  
  86.  
  87.  
  88. </script>
  89.  
  90. <br><br>
  91.  
  92. <script type="text/javascript">
  93.  
  94. function createOrder()
  95. {
  96.  
  97. coffee=document.forms[0].coffee;
  98. txt="";
  99. for (i=0;i<coffee.length;++ i)
  100. {
  101. if (coffee[i].checked)
  102. {
  103. txt=txt + coffee[i].value + " ";
  104. }
  105. }
  106. document.getElementById("order").value="You ordered a coffee with " + txt + "and options.";
  107. }
  108.  
  109. function check(whip)
  110. {
  111. document.getElementById("answer").value=whip;
  112. }
  113.  
  114. function flavor()
  115. {
  116. var mylist=document.getElementById("myList");
  117. document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text;
  118. }
  119.  
  120. </script>
  121.  
  122.  
  123.  
  124. </head>
  125.  
  126. <body>
  127.  
  128. <p>What would you like to drink?</p>
  129. <form>
  130. <p>
  131. <input type="checkbox" name="drink" value="coffee">coffee<br />
  132. <input type="checkbox" name="drink" value="tea">tea<br />
  133. <p>
  134. <input type="radio" name="browser" onclick="check(this.value)" value="with milk">With Milk<br />
  135. <input type="radio" name="browser" onclick="check(this.value)" value="extra milk">With Extra Milk<br />
  136. <input type="radio" name="browser" onclick="check(this.value)" value="light milk">With Light Milk<br />
  137. <input type="radio" name="browser" onclick="check(this.value)" value="no milk">No Milk<br />
  138. <br />
  139. Your milk preference is: <input type="text" id="answer" size="20">
  140. <p>
  141.  
  142. What size would you like?: <input type="text" size="20" value="Enter small, medium or large here" />
  143. <p>
  144. Would you like it hot, cold or blended?: <input type="text" size="20" value="Enter hot, cold or blended here" />
  145. <p>
  146. Would you like sugar?: <input type="text" size="20" value="Enter yes or no here" />
  147. <p>
  148. Select your favorite flavor:
  149. <select id="myList" onchange="flavor()">
  150. <option></option>
  151. <option>Vanilla</option>
  152. <option>Mint</option>
  153. <option>Butterscotch</option>
  154. </select>
  155. <p>Your favorite flavor is: <input type="text" id="favorite" size="20"></p>
  156. <p>
  157. <input type="button" onclick="formReset()" value="Reset">
  158. <p>
  159. <input type="button" onclick="createOrder()" value="Submit order">
  160. <br /><br />
  161. <input type="text" id="order" size="50">
  162. </form>
  163.  
  164.  
  165.  
  166. <br><br>
  167.  
  168. <a href="mailto:my_email@yahoo.com">Send e-mail</a>
  169.  
  170. </body>
  171.  
  172. </html>
Last edited by peter_budo; Apr 7th, 2008 at 9:29 am. Reason: Correction of opening code tag
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,419
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 229
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: JavaScript form validation - please help

 
0
  #2
Apr 7th, 2008
This is a little function I wrote to verify form fields, all you need is an div with the id "error" to take the output.
  1. /**
  2.  * Make sure required fields are set on a form
  3.  *
  4.  * @param elements Array of required field IDs
  5.  * @param parentForm ID of the form
  6.  * @param setvalTar ID of a hidden field to be set(optional)
  7.  * @param setval Value for setvalTar
  8.  */
  9. function verifyForm(elements,parentForm,setvalTar,setVal)
  10. {
  11. var valid = true;
  12. for(i=0;i<(elements.length);i++){
  13. $(elements[i]).className = ($(elements[i]).value == "")?'txtError':null;
  14. valid = ($(elements[i]).value == "")?false:valid;
  15. }
  16. $('error').style.display = (valid)?'none':'';
  17. $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
  18. if(setvalTar != null && setVal != null)
  19. setValue(setvalTar,setVal);
  20. if(parentForm != null && valid)
  21. $(parentForm).submit();
  22. else return valid;
  23. }
Then in an html form you would have something like
  1. <div id='error'></div>
  2. <form action="blah.php" method="post">
  3. <input type="text" name="fname" id="fname" />
  4. <input type="text" name="lname" id="lname" />
  5. <input type="button" onclick="if(verifyForm(['fname','lname'])){window.location='test.php';}" />
  6. </form>
Last edited by ShawnCplus; Apr 7th, 2008 at 12:26 pm.
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,419
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 229
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: JavaScript form validation - please help

 
0
  #3
Apr 7th, 2008
Almost forgot, for that to work you need this little line, I always forget it
  1. function $(id){return document.getElementById(id);}
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Join Date: Nov 2007
Posts: 8
Reputation: Gia is an unknown quantity at this point 
Solved Threads: 0
Gia's Avatar
Gia Gia is offline Offline
Newbie Poster

Re: JavaScript form validation - please help

 
0
  #4
Apr 7th, 2008
Thanks! I'll try this.
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 7,642
Reputation: ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of 
Solved Threads: 471
Super Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Failure as a human

Re: JavaScript form validation - please help

 
1
  #5
Apr 8th, 2008
> This is a little function I wrote to verify form fields, all you need is an div with the id "error" to
> take the output.

A required addition to that script would be checking whether the element really exists and trimming the form values before comparing them with an empty string so that I can't get away by keying in just a few whitespace characters.
I don't accept change; I don't deserve to live.

Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,419
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 229
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: JavaScript form validation - please help

 
0
  #6
Apr 8th, 2008
Good looking out ~s.o.s~, maybe something along the lines of this.
  1. /**
  2.  * Make sure required fields are set on a form
  3.  *
  4.  * @param elements Array of required field IDs
  5.  * @param parentForm ID of the form
  6.  * @param setvalTar ID of a hidden field to be set(optional)
  7.  * @param setval Value for setvalTar
  8.  */
  9. function verifyForm(elements,parentForm,setvalTar,setVal)
  10. {
  11. var valid = true;
  12. for(i=0;i<(elements.length);i++){
  13. if($(elements[i]))
  14. {
  15. $(elements[i]).value = $(elements[i]).value.replace(/^\s(.*)/,'$1');
  16. $(elements[i]).className = ($(elements[i]).value == "")?'txtError':null;
  17. valid = ($(elements[i]).value == "")?false:valid;
  18. }
  19. else valid = false;
  20. }
  21. $('error').style.display = (valid)?'none':'';
  22. $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
  23. if(setvalTar != null && setVal != null)
  24. setValue(setvalTar,setVal);
  25. if(parentForm != null && valid)
  26. $(parentForm).submit();
  27. else return valid;
  28. }

Aside from that, I also forgot to mention that you must have a CSS class that is applied to the textbox if there is an error, in this case it is called txtError but you can name it whatever you like and just change the code.
Last edited by ShawnCplus; Apr 8th, 2008 at 3:31 pm.
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 7,642
Reputation: ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of 
Solved Threads: 471
Super Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Failure as a human

Re: JavaScript form validation - please help

 
0
  #7
Apr 8th, 2008
A tad inefficient considering that you do the $('someId') thing again. It is in the end a call to document.getElementById() which basically traverses the entire in-memory DOM of the entire HTML document. Cache / store a reference to your Javascript objects whenever possible.

A better way of accessing form elements would be by using their name. Assuming that you need to access the value of a form control named 'txtName' , forms["formName"].elements["txtName"].value should do the trick. Make your function accept the form object as well.

Your regex trims only leading whitespaces (you can key in that regex at the Firefox error console and see for yourself). A complete regex would be yourStr.replace(/(^\s+)|(\s+$)/g, '')
Other than the things mentioned above, you are good to go. :-)
Last edited by ~s.o.s~; Apr 8th, 2008 at 3:42 pm.
I don't accept change; I don't deserve to live.

Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,419
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 229
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: JavaScript form validation - please help

 
0
  #8
Apr 8th, 2008
This sort of turned into a thread about my function but would this work or no?
  1. /**
  2.  * Make sure required fields are set on a form
  3.  *
  4.  * @param elements Array of required field IDs
  5.  * @param parentForm ID/Name of the form
  6.  * @param setvalTar ID of a hidden field to be set(optional)
  7.  * @param setval Value for setvalTar
  8.  */
  9. function verifyForm(elements,parentForm,setvalTar,setVal)
  10. {
  11. var valid = true;
  12. parent = $(parentForm);
  13. if(!parent) parent = forms[parentForm];
  14. for(i=0;i<(elements.length);i++){
  15. if(parent.action) //will this work to make sure it's a form?
  16. elem = parent.elements[elements[i]];
  17. else
  18. elem = $(elements[i]);
  19. if(elem)
  20. {
  21. elem.value = elem.value.replace(/(^\s+)|(\s+$)/g, '');
  22. elem.className = (elem.value == "")?'txtError':null;
  23. valid = (elem.value == "")?false:valid;
  24. }
  25. else valid = false;
  26. }
  27. $('error').style.display = (valid)?'none':'';
  28. $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
  29. if(setvalTar != null && setVal != null)
  30. setValue(setvalTar,setVal);
  31. if(parentForm != null && valid)
  32. $(parentForm).submit();
  33. else return valid;
  34. }
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 7,642
Reputation: ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of 
Solved Threads: 471
Super Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Failure as a human

Re: JavaScript form validation - please help

 
0
  #9
Apr 8th, 2008
Yes, except that you don't need to get the form element by ID. In the calling function, instead of passing the form ID, pass the form object.
verifyForm(..., this.form);
I don't accept change; I don't deserve to live.

Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,419
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 229
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: JavaScript form validation - please help

 
0
  #10
Apr 8th, 2008
Well I did that as a name or ID so they could either give a form or some other element as a parent (which realizing now would break the submit() call)
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the JavaScript / DHTML / AJAX Forum
Thread Tools Search this Thread



Tag cloud for JavaScript / DHTML / AJAX
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC