Welcome Guest!

If you do not have an account yet on The Web Squeeze forums, please Register! It’s FREE and there are many benefits:

  • Receive Fast Advice
  • Learn Programming Languages
  • Get Professional Website Reviews
  • Quick Troubleshooting Assistance

> Form Validation

This is a discussion on Form Validation, within the Javascript section. This forum and the thread "Form Validation" are both part of the Programming Your Website category.

2 Pages V   1 2 >  
Reply to this topicStart new topic
> Form Validation
Monie
post Jun 1 2008, 10:08 PM
Post #1


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Ok, I know basic form validation but when it comes to validating a form with more than 50 field then I have to go to google to search for the script. Here is some JS script for validating a form that I have found but for every empty field it will popup an alert message which is not a good way of doing it biggrin.gif

My question is, what is the best way of validating a form which have 50+ field to be validated with a single prompt (alert user which field is empty) upon submiting the form. Thanks...

CODE
<script language="javascript">
     function validate()
     {
     submitOK="True"
     // Form Field Information
     if (document.validateForm.FirstName.value == "")
      {
      alert("Please enter your First Name.")
      submitOK="False"
      }
     if (document.validateForm.LastName.value == "")
      {
      alert("Please enter your Last Name.")
      submitOK="False"
      }
     if (document.validateForm.Email.value == "")
      {
      alert("Please enter your Email Address.")
      submitOK="False"
      }
if (submitOK=="False")
      {
      return false
      }
     }
     </script>


--------------------

Go to the top of the page
 
+Quote Post
Rakuli
post Jun 1 2008, 11:56 PM
Post #2


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


Hey Monie,

Let's hope I can give you some more Javascript help today...

CODE
function validateForm()
{
    // Start by getting all the elements in the form
    
    var eles = document.forms['validateForm'].elements;
    var nm = eles.length;

    var errorMsg = ''; // Initialise an empty error message

    // Now loop through all of the elements in the form and ensure there is a value set for them
    for (i=0; i< eles.length; i++)
    {
         if (eles[i].value.replace(/[\s]/, '') == '')
         {
                errorMsg += 'Please enter a value in ' + eles[i].name + '\n';
         }
     }

// If the errorMsg has anything but an empty string then alert and return false
    if (errorMsg == '')
        return true;
    else
        alert(errorMsg);
    return false;
}



That will loop through all the elements in a form and add any empty values to a variable errorMsg and alert the user once finished. It has some limitations like not doing checkboxes or radios but it is a nice simple start.

If you do have checkboxes or radios then it gets a little more complicated but not by much, let me know if you want an example of how that would work.

Cheers,


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
Monie
post Jun 2 2008, 12:39 AM
Post #3


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


You are the man Rakuli.
You just save my time "hanging out" in google biggrin.gif
At this moment, my form doesn't have any radio or checkbox. If I do need it, I know where to find you biggrin.gif

I have one question with the script. What does the "replace(/[\s]/, '')" are for?
CODE
if (eles[i].value.replace(/[\s]/, '') == '')


Thanks mate!
P/S: hows your new job?


--------------------

Go to the top of the page
 
+Quote Post
Rakuli
post Jun 2 2008, 01:00 AM
Post #4


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


QUOTE
I have one question with the script. What does the "replace(/[\s]/, '')" are for?
CODE
if (eles.value.replace(/[\s]/, '') == '')


Thanks mate!
P/S: hows your new job?


The /[\s]/ is a regular expression. In javascript testing against value = '' isn't reliable because even one space in the input will mean that it has something and will get past the validation.

The regular expression is searching for any whitespace character, replacing it with nothing and [i]then
testing to see if it is empty. Much more reliable wink.gif


New job is great mate, absolutely loving it wink.gif Get to code until my heart is content, just the way I like it.

You still enjoying your new post?


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
Monie
post Jun 2 2008, 02:55 AM
Post #5


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Ahh.. thanks for the tips!
New job? I enjoy my new job to be honest in fact I soon will be on the conformation list as I have completed my 3 month probation biggrin.gif
Hopefully there will be some increment!

Anyway, thanks mate for that lovely script of yours!
You are my Javascript guru, hehehehe...


--------------------

Go to the top of the page
 
+Quote Post
velo
post Jun 2 2008, 01:14 PM
Post #6


Rapid Squeezer
****

Posts: 182
Joined: 19-February 08
From: Netherlands


QUOTE (Rakuli @ Jun 2 2008, 06:56 AM) *
CODE
          if (eles[i].value.replace(/[\s]/, '') == '')
              {
                     errorMsg += 'Please enter a value in ' + eles[i].name + '\n';
              }


You can also use the above and do something like:
CODE
if (eles[i].value.replace(/[\s]/, '') == '') {
   eles[i].style.backgroundColor = "red";
}


instead of the errorMsg, and simply alert "Please fill in the fields that are marked red" or something. Also a fun thing to do, and very precise visual info for your visitor.
Play around with it smile.gif

Rakuli, by the way, i think your example is programmed so that *all* elements in a form need to be filled in. How would you change it so that some are not mandatory?

This post has been edited by velo: Jun 2 2008, 01:15 PM


--------------------

fresh-style.nl - small webdesign & development projects
Go to the top of the page
 
+Quote Post
Rakuli
post Jun 2 2008, 04:05 PM
Post #7


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


QUOTE
Rakuli, by the way, i think your example is programmed so that *all* elements in a form need to be filled in. How would you change it so that some are not mandatory?



You could give the form elements a class of mandatory

CODE
function validateForm()
{
    // Start by getting all the elements in the form
    
    var eles = document.forms['validateForm'].elements;
    var nm = eles.length;

    var errorMsg = ''; // Initialise an empty error message

    // Now loop through all of the elements in the form and ensure there is a value set for them
    for (i=0; i< eles.length; i++)
    {
         if (eles[i].value.replace(/[\s]/, '') == '' && eles[i].className.indexOf('mandatory') != -1)
         {
                errorMsg += 'Please enter a value in ' + eles[i].name + '\n';
                eles[i].style.backgroundColor ='#FF0000';
         }
     }

// If the errorMsg has anything but an empty string then alert and return false
    if (errorMsg == '')
        return true;
    else
        alert(errorMsg);
    return false;
}


Now only the form elements that have a class of mandatory will trigger an alert. It also allows you to style them differently in the stylesheet beforehand.


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
velo
post Jun 2 2008, 04:40 PM
Post #8


Rapid Squeezer
****

Posts: 182
Joined: 19-February 08
From: Netherlands


Ah ofcourse... that's sweet man. Much better than checking everything 1 by 1 and still be free of choice for mandatory fields. I'll remember that one.


--------------------

fresh-style.nl - small webdesign & development projects
Go to the top of the page
 
+Quote Post
Monie
post Jun 3 2008, 01:03 AM
Post #9


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Wow.. thanks both of you guys!
That extra tips really makes me happy biggrin.gif hehehe

Ok, just a quick question.
  1. eles[i].style.backgroundColor ='#FF0000';
    Is there any other properties like this that I can put in just to get more control over it?
  2. Currently, the alert message will take the field name right, something like "Please enter a value in ' + eles[i].name + '"
    Can we specify other instead of the field name? To make the alert more beautiful, I have to set the field name to be understandable like "Name" instead of "txtName"


Cheers...


--------------------

Go to the top of the page
 
+Quote Post
Rakuli
post Jun 3 2008, 01:41 AM
Post #10


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


You can do this by creating an array of values in Javascript. This array will have indexes of the form names (txtName) and the value of the array will be the actual value that you want to show the user (Name)

The we modify the above function just slightly to check if there is a human readable field name to use instead of the name.

CODE
// Create the array of Human Field Names here

var HumanFieldNames = new Array();

HumanFieldNames['txtName'] = 'Name Field';
HumanFieldNames['phNum'] = 'Phone Number Field';


function validateForm()
{
    // Start by getting all the elements in the form
    
    var eles = document.forms['validateForm'].elements;
    var nm = eles.length;

    var errorMsg = ''; // Initialise an empty error message

    // Now loop through all of the elements in the form and ensure there is a value set for them
    for (i=0; i< eles.length; i++)
    {
         if (eles[i].value.replace(/[\s]/, '') == '' && eles[i].className.indexOf('mandatory') != -1)
         {
                errorMsg += 'Please enter a value in ' + (typeof(HumanFieldNames[eles[i].name]) != 'undefined' ?  HumanFieldNames[eles[i].name] : eles[i].name) + '\n';
                eles[i].style.backgroundColor ='#FF0000';
         }
     }

// If the errorMsg has anything but an empty string then alert and return false
    if (errorMsg == '')
        return true;
    else
        alert(errorMsg);
    return false;
}



QUOTE
eles[i].style.backgroundColor ='#FF0000';
Is there any other properties like this that I can put in just to get more control over it?


Any element can have all of its CSS properties changed through its style object. The only difference between the CSS name and the Javascript name is that instead of string two words together with hyphens : background-color, you use Javascript notation which is all small letters for the first word and them capitalise the first letter of the second word : backgroundColor


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
velo
post Jun 3 2008, 05:04 PM
Post #11


Rapid Squeezer
****

Posts: 182
Joined: 19-February 08
From: Netherlands


Although you can use the names in a alertbox, personally i would say to keep the alert message a general statement, instead of summing up all the missing fields. If someone is very stupid and misses 10 fields, you'll have a very long alert box. Again, that's my personal opinion and only if you like the backgroundColor, because with that, it's obvious enough what they need to fill in. smile.gif

Good luck.


--------------------

fresh-style.nl - small webdesign & development projects
Go to the top of the page
 
+Quote Post
Monie
post Jun 4 2008, 05:21 AM
Post #12


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Thanks guys for the extra brilliant tips:D


--------------------

Go to the top of the page
 
+Quote Post
Rakuli
post Jun 4 2008, 05:54 AM
Post #13


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


If you wanted to get really carried away? Instead of using an alert message, you can insert a red text message after the field that is missing.

Referring back to the javascript so far, we make a couple more changes:

CODE
// Create the array of Human Field Names here

var HumanFieldNames = new Array();

HumanFieldNames['txtName'] = 'Name Field';
HumanFieldNames['phNum'] = 'Phone Number Field';

function validateForms(dform)
{
    // Start by getting all the elements in the form

    var eles = dform.elements;

    var nm = eles.length;

    var errorMsg = ''; // Initialise an empty error message

    // Now loop through all of the elements in the form and ensure there is a value set for them
    for (i=0; i< eles.length; i++)
    {
         // check if an error node has already been created and deleted it if it is
         // reset the background color as well
         if (document.getElementById('after_input' + i))
         {
             document.getElementById('after_input' + i).parentNode.removeChild(document.getElementById('after_input' + i));
             eles[i].style.backgroundColor = '';
        }
         if (eles[i].value.replace(/[\s]/, '') == '' && eles[i].className.indexOf('mandatory') != -1)
         {
                 
               // Create a new element in the document
               var new_span = document.createElement('span');
                     new_span.setAttribute('id', 'after_input' + i);
              // Add some styles to the element
                     new_span.style.color = "#FF0000";
                     new_span.style.fontWeight = "bold";
              // Create the error text message
                     errorMsg = document.createTextNode('Please enter a value in ' + (typeof(HumanFieldNames[eles[i].name]) != 'undefined' ?  HumanFieldNames[eles[i].name] : eles[i].name));
              // attach the error text to our new div
                    new_span.appendChild(errorMsg);

              // Add this new span as the next element in the document after the input
              if (eles[i] == eles[i].parentNode.lastChild)
                  eles[i].parentNode.appendChild(new_span);
              else
                  eles[i].parentNode.insertBefore(new_span, eles[i].nextSibling);


                                eles[i].style.backgroundColor ='#FF0000';
         }
     }

// If the errorMsg has anything but an empty string then alert and return false
    if (errorMsg == '')
        return true;

    return false;
}


Now it will add a span next to the input if the value is missing and remove it when it has a value. All using the DOM of course biggrin.gif


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
Monie
post Jun 4 2008, 07:35 AM
Post #14


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Mind if you could post in the HTML code too!
This code is getting brilliant biggrin.gif


--------------------

Go to the top of the page
 
+Quote Post
Rakuli
post Jun 4 2008, 07:41 AM
Post #15


Squeeze Machine
Group Icon

Posts: 766
Joined: 13-February 08
From: Catching the squeezed drips downunder.


The html is just any form you want wink.gif Just add onsubmit="validateForms(this)" to the form you want to use and follow the rest of the steps found in this thread.


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
Monie
post Jun 4 2008, 07:49 AM
Post #16


Squeeze Machine
*****

Posts: 733
Joined: 13-February 08
From: Borneo


Yup! My mistake.
I have chanced some of the variable name, like the function name and when I pasted in your new brilliant function, I forgot to amend the variable name to match me one biggrin.gif

Anyway, thanks again mate!
This is going to be my form validation "style" if I ever needed to do some other form validation in the future.
Surely it will be your name on top of the script description