ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)