Hi all. A JavaScript beginner looking for help to make form validation more user-friendly. I found the following function on the web and modified it slightly for my form, and it works fine as far as it goes. I have added class="REQUIRED" to the tag of form fields that are compulsory, and there's an e-mail field which has class="REQUIRED EMAIL". My question is, how do I clearly indicate in the alert box the field that is being referred to? For example, can I add some otherwise harmless element to the tag of REQUIRED fields and have it printed out in the alert box? So the alert box would read something like "Please fill out this field: Contact Name". <script> function validateFields() { var elements = document.forms["form1"].elements; var emailPattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/; for (var i = 0; i < elements.length; i++) { if (/(^| )REQUIRED( |$)/.test(elements[i].className) && elements[i].value == "") { [B][COLOR="DarkRed"] elements[i].focus(); alert("Please fill out this field.");[/COLOR][/B] return false; } if (/(^| )EMAIL( |$)/.test(elements[i].className) && !emailPattern.test(elements[i].value)) { elements[i].focus(); alert("Please provide a valid e-mail address."); return false; } } } Code (markup):
elements (inside of the for loop) contains the field object. To read the field name just use: elements.name Ex. alert('Please fill out the ' + elements.name + ' field.'); The problem is that now if your users have more than 1 empty field they are going to get more than 1 alert box. Getting spammed by alert boxes is very frustrating as a user. Another issue is if your validation is client side (javascript) then users without javascript enabled can just bypass it completely. To fix this I'll leave you with an exercise. Think of a way where you can write your validation code using a server side language (PHP, ASP, etc.) but still have real time feedback for users who have javascript enabled as well as only having to write the validation rules once (ie. on page submit without javascript enabled the user will still see the feedback but instead of real time they have to submit the page first). Search Google for: "form validation ajax", "form validation php", "form validation json response". That should help you get started. Replace "php" if you happen to be using something else.
I'd advise using <div> tags above the failed input box instead of popups bc popups are really annoying and it'll help tell users where they are going wrong. Don't forget to use PHP serverside validation also bc people can easily hack javascript.
Thank you both your input. Yes, I'm aware of the potential annoyance factor of multiple alert boxes, and I have some sample code I need to play with that provides in-line error messages. But in the meantime I just needed to get the alerts working properly. Your responses much appreciated.