ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

How to Validate HTML Input Using JavaScript

Updated on October 15, 2011

The author maintains an ongoing concern for information security due to specializing his career opportunities in network engineering and concentrating his graduate degrees in information security. The fact that programming errors cause problems in network infrastructure implementations is hardly disputed but network engineer are typically not adept to solve those types of problems; they ride with the programmers. Programmers must write programs that validate data before those programs pass that data along to the network.

Many vulnerabilities in the realm of Information Security result from passing bad data to applications. Buffer overflows and SQL injection are just a couple of the vulnerabilities that may permit a hacker access to a system when input data has not been validated. Buffer overflows occur when input data runs past the limits of an established buffer space and SQL injection may result from passing a query placed in an input field to a database server.

The hub entitled Create a Simple Form in HTML provided a brief tutorial to guide a novice programmer through the task of creating a simple form to capture contact information. If a reader of that hub were to use the created form in a production network environment then the above mentioned security vulnerabilities would provide a possible path for attack because the data was not validated.

So, how can a programmer validate the data and what should the programmer look for? Write a function to check each of the fields in the form. For this simple form there are only a few characteristics of the data that the programmer should check

The programmer should check the sizes and types of strings to ensure that what the user inputs matches what the programmer expects. Data should also be checked for simple existence; you do not want a user submitting an empty form. This wastes bandwidth and server resources.


JavaScript: The HTML Stimulant
JavaScript: The HTML Stimulant

Check for Null Fields

The simplest test would be to check for the existence of data. All that is necessary is to check each field and make sure that those fields are not blank. A field that contains no data is a null field. Let's take a look at our simple contact information form and check each of the fields to make sure that the user entered something in those fields before he submitted the form.

To accommodate the test, we will first create an overall function to control each of the testing procedures. In our example, we call the function checkFormData and will take action when called by a user pressing the Commit button in the form (the name of the button in the form has not changed but the action has). The function is referred to as a dispatcher function because the function simply calls other functions and, in this case,those functions perform the validation tasks. The code snippet for the dispatcher function follows:

Dispatcher Function

<script type="text/javascript>
  function checkFormData() {
    dataNptNull();
    dataNotTooLong();
  }
</script>

Notice that the dispatcher function's only purpose is to call other functions and in this case the two called functions are named dataNotNull() and dataNotTooShort(). The programmer has the option to assign whatever name to a function he desires but a good philosophy is to assign names that give meaning to the code to simplify later maintenance.

The two functions illistrated in the hub check for null data and data length. The programmer could add other tests by simply writing the code for the functions and adding the function calls to the dispatcher module. The rest of the program would not require modification bnecause all the validation would occur within the dispatched functions..

Now, let's check the form for empty data fields in the dataNotNull() function:

<script type="text/javascript">
  function dataNotNull() (
    var goodData;
    goodData = true;
    var testData;
    testData=document.contactForm.fname.value;
    if (test==null || testData=="") {
      alert("Please enter your First Name!");
      goodData = false;
    }
    else {
      testData=document.contactForm.lname.value;
      if (testData==null || testData=="") {
        alert("Please enter your Last Name!");
        goodData = false;
      }
    }
    else 
      testData=document.contactForm.email.value;
      if (testData==null || testData=="") {
        alert("Please enter your e-mail address!");
        goodData = false;
      }
    return goodData;
  }
</script>
Click image to enlarge
Click image to enlarge

The screen shot to the right displays the warning message displayed when a user enters a blank First Name. Similar warning messages appear as a result of the user entering no information in the other two fields as well. JavaScript includes the alert() function to display warning messages and the code takes advantage of this function, which eliminates much additional coding.

The function then successively extracts the values from the fields and compares those values to a null character represented by the double equal sign followed by double quotation marks (=="") in the if statements. The double equal sign (==) is not a typo but is used as a comparison operator in many programming languages, including JavaScript. The document.contactForm.XXXX.value parameter uses the Document Object Model (DOM) to extract the data, where XXXX equals fname, lname, or email.

This seems like a fair amount of code to simply check for null values and you may be wandering if there is a shorter way to accomplish the task. Well, there is using modularization but that topic is outside the scope of this hub. There will be more on modularization in later hubs.

Length Validation

Now that we know that the fields contain data or not, we can move on to validate the length of the data. If you refer to the contact form, you may notice that each of the input fields include a size attribute. This attribute specifies the number of characters that a user may supply in that field.

Since we know what size each field should be, we can use that figure as a comparison to the size of the data field the user supplied to validate the length of each of the fields. Validating the size of the fields helps prevent buffer overflows, which can crash programs or worse, permit a hacker the ability to take control of the system.

The following code snippet demonstrates one method to validate the length of the fields:

Length Validation

<script type="text/javascript">

  function dataNotLong(){
    var goodData;
    goodData = true;
    var testData=document.contactForm.fname.value;
    if (testData.length>25) {
       alert("The field must be no more than 25 characters!");
       goodData=false;
    }
    else {
      var testData=document.contactForm.lname.value;
      if (testData.length>25) {
        alert("The field must be no more than 25 characters!");
        goodData=false;
    }
    else {
      var testData=document.contactForm.email.value;
      if (testData.length>25) {
       alert("The field must be no more than 25 characters!");
       goodData=false;
    }
    return goodData;
  }
</script>

The preceding code checks the length of each of the data fields in the form against a maximum length of 25 characters. The size="25" attribute in each of the form's input fields establishes the size of those fields and of the associated buffers. If the size is exceeded the the validation function displays an error message.

Other validation tests for the form data would include tests for character content and a valid format for the email field. Those tests are left as an exercise for you to demonstrate your ability to create validation tests on your own.

Note: These tests perform simple validation within the client's browser but should not replace validation tests on the server side because the server should not trust the validity of data received from the client. This means that the tests should be performed on both sides of a connection.

The contact form that was created earlier is included at the end of this hub for reference so you can check the names of the fields and functions between the form and the validation functions.

Contact Information Form

<form id="contactForm" name="contactForm">
  <table style="background-color:silver" border=1>
    <tr><td> Your First Name</td><td><input id="fname" name="fname" size="25" /></td></tr>
    <tr><td> Your Last Name</td><td><input id="lname" name="lname" size="25" /></td></tr>
    <tr><td> Your E-mail</td><td><input id="emAddress" name="emAddress" size="25" /></td></tr>
    <tr><td>
    <!-- Clicking the Commit button invokes the checkFormData() function in the <script> section above -->
      <td><input type="button" onclick="commitData()" value="Commit" /></td>
    </tr>
  </table>
</form>

Was this hub helpful?

The author appreciates all comments.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      aravinth 5 years ago

      it's more use full for html and java script...