| | |
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
![]() |
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:
html Syntax (Toggle Plain Text)
<html> <head> <title>Gia's Web Page</title> <link type="text/css" rel="stylesheet" href="style3.css" > </head> <body> <!-- Comment: Introduction --> <a name="introduction"></a> <h1>This is my <b>Individual Programming Assignment #1</b>.</h1> <br><br> <!-- Comment: Purpose --> <h3><i>This page has been developed by Gia.</i></h3> <br><br> <img src="tulip.jpg" style="opacity:0.4;filter:alpha(opacity=40)" onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100" onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" /><img src="tulip2.jpg" style="opacity:0.4;filter:alpha(opacity=40)" onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100" onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" /> <br><br> <span id="spnWelcome"></span> <body onLoad="greetUser()"> <script type="text/javascript"> function greetUser() { // Prompt the user for their name var usersName = prompt("Hi. What is your name?", ""); // Get an object reference to the <span> tag var welcomeTag = document.getElementById("spnWelcome"); // Create an array to hold month names var monthNames = new Array(); // Populate array with month names monthNames[0] = 'January'; monthNames[1] = 'February'; monthNames[2] = 'March'; monthNames[3] = 'April'; monthNames[4] = 'May'; monthNames[5] = 'June'; monthNames[6] = 'July'; monthNames[7] = 'August'; monthNames[8] = 'September'; monthNames[9] = 'October'; monthNames[10] = 'November'; monthNames[11] = 'December'; // Get current date/time var today = new Date(); // 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 // out perfectly with the fact that getMonth() returns a 0-based month index. month = today.getMonth(); // Get the day of the month var day = today.getDate(); // Get the full year var year = today.getFullYear(); // Format the date in the following format: MonthName day, year var formattedDate = monthNames[month] + ' ' + day + ', ' + year; // Replace the content of the <span> tag with a personalized message welcomeTag.innerHTML = 'Hi ' + usersName + '!!! Welcome to my Website! <br>Today is: ' + formattedDate; } </script> <br><br> <script type="text/javascript"> function createOrder() { coffee=document.forms[0].coffee; txt=""; for (i=0;i<coffee.length;++ i) { if (coffee[i].checked) { txt=txt + coffee[i].value + " "; } } document.getElementById("order").value="You ordered a coffee with " + txt + "and options."; } function check(whip) { document.getElementById("answer").value=whip; } function flavor() { var mylist=document.getElementById("myList"); document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text; } </script> </head> <body> <p>What would you like to drink?</p> <form> <p> <input type="checkbox" name="drink" value="coffee">coffee<br /> <input type="checkbox" name="drink" value="tea">tea<br /> <p> <input type="radio" name="browser" onclick="check(this.value)" value="with milk">With Milk<br /> <input type="radio" name="browser" onclick="check(this.value)" value="extra milk">With Extra Milk<br /> <input type="radio" name="browser" onclick="check(this.value)" value="light milk">With Light Milk<br /> <input type="radio" name="browser" onclick="check(this.value)" value="no milk">No Milk<br /> <br /> Your milk preference is: <input type="text" id="answer" size="20"> <p> What size would you like?: <input type="text" size="20" value="Enter small, medium or large here" /> <p> Would you like it hot, cold or blended?: <input type="text" size="20" value="Enter hot, cold or blended here" /> <p> Would you like sugar?: <input type="text" size="20" value="Enter yes or no here" /> <p> Select your favorite flavor: <select id="myList" onchange="flavor()"> <option></option> <option>Vanilla</option> <option>Mint</option> <option>Butterscotch</option> </select> <p>Your favorite flavor is: <input type="text" id="favorite" size="20"></p> <p> <input type="button" onclick="formReset()" value="Reset"> <p> <input type="button" onclick="createOrder()" value="Submit order"> <br /><br /> <input type="text" id="order" size="50"> </form> <br><br> <a href="mailto:my_email@yahoo.com">Send e-mail</a> </body> </html>
Last edited by peter_budo; Apr 7th, 2008 at 9:29 am. Reason: Correction of opening code tag
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.
Then in an html form you would have something like
javascript Syntax (Toggle Plain Text)
/** * Make sure required fields are set on a form * * @param elements Array of required field IDs * @param parentForm ID of the form * @param setvalTar ID of a hidden field to be set(optional) * @param setval Value for setvalTar */ function verifyForm(elements,parentForm,setvalTar,setVal) { var valid = true; for(i=0;i<(elements.length);i++){ $(elements[i]).className = ($(elements[i]).value == "")?'txtError':null; valid = ($(elements[i]).value == "")?false:valid; } $('error').style.display = (valid)?'none':''; $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>'; if(setvalTar != null && setVal != null) setValue(setvalTar,setVal); if(parentForm != null && valid) $(parentForm).submit(); else return valid; }
html Syntax (Toggle Plain Text)
<div id='error'></div> <form action="blah.php" method="post"> <input type="text" name="fname" id="fname" /> <input type="text" name="lname" id="lname" /> <input type="button" onclick="if(verifyForm(['fname','lname'])){window.location='test.php';}" /> </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.
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.
Almost forgot, for that to work you need this little line, I always forget it 

javascript Syntax (Toggle Plain Text)
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.
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.
> 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.
> 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
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
Good looking out ~s.o.s~, maybe something along the lines of this.
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.
javascript Syntax (Toggle Plain Text)
/** * Make sure required fields are set on a form * * @param elements Array of required field IDs * @param parentForm ID of the form * @param setvalTar ID of a hidden field to be set(optional) * @param setval Value for setvalTar */ function verifyForm(elements,parentForm,setvalTar,setVal) { var valid = true; for(i=0;i<(elements.length);i++){ if($(elements[i])) { $(elements[i]).value = $(elements[i]).value.replace(/^\s(.*)/,'$1'); $(elements[i]).className = ($(elements[i]).value == "")?'txtError':null; valid = ($(elements[i]).value == "")?false:valid; } else valid = false; } $('error').style.display = (valid)?'none':''; $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>'; if(setvalTar != null && setVal != null) setValue(setvalTar,setVal); if(parentForm != null && valid) $(parentForm).submit(); else return valid; }
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.
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.
A tad inefficient considering that you do the
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
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
Other than the things mentioned above, you are good to go. :-)
$('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
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
This sort of turned into a thread about my function but would this work or no?
javascript Syntax (Toggle Plain Text)
/** * Make sure required fields are set on a form * * @param elements Array of required field IDs * @param parentForm ID/Name of the form * @param setvalTar ID of a hidden field to be set(optional) * @param setval Value for setvalTar */ function verifyForm(elements,parentForm,setvalTar,setVal) { var valid = true; parent = $(parentForm); if(!parent) parent = forms[parentForm]; for(i=0;i<(elements.length);i++){ if(parent.action) //will this work to make sure it's a form? elem = parent.elements[elements[i]]; else elem = $(elements[i]); if(elem) { elem.value = elem.value.replace(/(^\s+)|(\s+$)/g, ''); elem.className = (elem.value == "")?'txtError':null; valid = (elem.value == "")?false:valid; } else valid = false; } $('error').style.display = (valid)?'none':''; $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>'; if(setvalTar != null && setVal != null) setValue(setvalTar,setVal); if(parentForm != null && valid) $(parentForm).submit(); else return valid; }
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.
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.
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
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
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.
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.
![]() |
Similar Threads
- javascript required fields 290 form elements (JavaScript / DHTML / AJAX)
- validation (PHP)
- Simple JavavScript needs email validation (JavaScript / DHTML / AJAX)
- .net validation/javascript conflict (ASP.NET)
- PHP Quote form (PHP)
- User Form error checking (PHP)
- Need help with Javascript (JavaScript / DHTML / AJAX)
Other Threads in the JavaScript / DHTML / AJAX Forum
- Previous Thread: How to implement UDL as a connectionstring using javascript
- Next Thread: Positioning, Scrolling & FireFox
| Thread Tools | Search this Thread |
Tag cloud for JavaScript / DHTML / AJAX
ajax ajaxexample ajaxjspservlets array blackjack browser captcha captchaformproblem cart checkbox child class close codes date debugger dependent developer disablefirebug dom editor element embed engine events explorer ext file firefox flash form forms frameworks game getselection google gxt hiddenvalue highlightedword hint html ie7 ie8 iframe internet java javascript javascripthelp2020 jquery jsf jsfile jsp jump libcurl maps marquee masterpage math matrixcaptcha media object onerror onmouseoutdivproblem onreadystatechange parent passing paypal pdf php position post programming prototype rated redirect runtime safari scale scriptlets scroll search security session shopping size software sources star stars stretch synchronous toggle tweet unicode variables web webservice window wysiwyg \n






