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. className) && elements. value == "")
{
elements. focus();
alert("Please fill out this field. ");
return false;
}
if (/(^| )EMAIL( |$)/. test(elements. className) && !emailPattern. test(elements. value))
{
elements. focus();
alert("Please provide a valid e-mail address. ");
return false;
}
}
}