When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback
Print this page.
Published: Saturday, September 19, 1998

Form Validation Using Javascript


Introduction:
Client-side form validation is an important part of a web site where data needs to be collected from the user. Users are innately ignorant, and will mess up data entry in a web form if given the chance. This is one of life's few, succinct truisms. It i s the job of the web programmer, then, to make sure his pages which use forms include client-side form validation using JavaScript.

- continued -

If you are unfamiliar with JavaScript, then this may not be the best article for you, since we will supply mostly just code samples here. For JavaScript newbies, you may wish to check out other articles on this site, or you can always visit Netscape's JavaScript Site or Microsoft's JavaScript Site.


What do we need to Validate?
What needs to be validated is often up to the web programmer. It is his or her duty to determine how extensively he needs to fool-proof his web form. Often times you just need to make sure that required fields are entered. Other times you need to ensur e simply that the correct data type is entered; and still other times you need to make sure a user's input conforms to a certain standard (such as telephone numbers, social security numbers, etc.).

Let's look at an example. Let us say that you are wanting to collect information from your users about how they rate your site. You may have a form asking for the following fields:

  • Their full name
  • Their e-mail address (which you make optional)
  • A rank for the site ranging from 1 - 10

We would want to write a JavaScript function to ensure that the name field had a value in it, and that the site ranking had a value between 1 and 10 in it. Let's take a look at what the JavaScript would look like:


<SCRIPT LANGUAGE="JavaScript">
/*
   The isEmpty and isWhitespace functions were taken straight from Netscape's JavaScript development site, http://developer.netscape.com.
*/


      // whitespace characters
      var whitespace = " \t\n\r";

      /****************************************************************/

      // Check whether string s is empty.
      function isEmpty(s)
      { return ((s == null) || (s.length == 0)) }

      /****************************************************************/

      function isWhitespace (s)
      {
           var i;

           // Is s empty?
           if (isEmpty(s)) return true;

           // Search through string's characters one by one
           // until we find a non-whitespace character.
           // When we do, return false; if we don't, return true.

           for (i = 0; i < s.length; i++)
           {
                // Check that current character isn't whitespace.
                var c = s.charAt(i);

                if (whitespace.indexOf(c) == -1) return false;
           }

           // All characters are whitespace.
           return true;
      }

      /****************************************************************/

      function ForceEntry(val, str) {
           var strInput = new String(val.value);

           if (isWhitespace(strInput)) {
                alert(str);
                return false;
           } else
                return true;

      }

      /****************************************************************/

      function ValidateRanking() {
           // This function ensures document.forms[0].nRanking.value >=1 && <= 10

           if (parseInt(document.forms[0].nRanking.value) >= 1 && parseInt(document.forms[0].nRanking.value) <=10)
                return true;
           else
                return false;
      }

      /****************************************************************/

      function ValidateData() {
           var CanSubmit = false;

           // Check to make sure that the full name field is not empty.
           CanSubmit = ForceEntry(document.forms[0].txtName,"You supply a full name.");

           // Check to make sure ranking is between 1 and 10
           if (CanSumbit) CanSubmit = ValidRanking();

           return CanSubmit;
      }
</SCRIPT>



. . .



<!-- Of course, we would also need to hook the ONSUBMIT event for the form. Here is what the snippet of code should look like... -->

      <FORM NAME="frmSiteRanking" METHOD="GET" ACTION="SiteRanking.asp" ONSUBMIT="return ValidateData();">



<!-- The "return" prior to the function call, will cancel the submission of the form if the function returns false (which will happen if the user has invalid data), but will allow submission of the form if the function returns true (which will happen if the user enters valid data). Pretty simple, eh? Having the data valided on the client-side prevents the user from making multiple round-trips to the server if his or her data is incorrect in form or function. -->


Tips and Good Ideas:

  • It is often a good idea to put your common JavaScript validation functions into a common file, so you can include the file from all pages which need the form validation. In future examples in this article, I will assume that my standard functions (is Whitespace(s), isEmpty(s), and ForceEntry(val,str) are contained in a file called DataValidation.js).

  • Another good tip is to validate data on ALL fields in your forms. I know this may seem tedious and boring, but nothing is worse than having SQL errors, or inconsistent data in your database. Further down in this article, you will find several JavaScript examples for various types of validation. Feel free to use these on your web site.

  • It is wise to make your data validation functions as portable as possible. You don't want to have to write code but once.

  • Make use of the JavaScript string object. It has a lot of functionality that many people spend time programming themselves. If someone else has already done it, why do it yourself?

  • Above all, make your forms and data validation procedures user friendly, keeping in mind that users are innately ignorant. If a user is going to the trouble to submit information to you, make sure they don't have to work hard at it. Nothing is worse to an end user than being confronted with a series of errors once they have submitted personal information to you.


    JavaScript Validation Code:
    Here is a link to a text file containing many JavaScript data validation functions. Again, feel free to use these on your web site. (If someone's already written it, there's no need for you to.) To save this text file, just hold down shift and click the link below. Happy programming!


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article