Bright Java Tutorial

is brought to you by DoITBright LLC

Javascript

Javascript Validate HTML TextField

An HTML text object or most people call it either textfield or textbox is a means to key in alpha numeric characters as input in an HTML form. This is accomplished by including the <input> tag with an attribute of 'type' equal to 'text' between the <form> and </form> tags. When working with textbox, most often, we need to perform validation on it or manipulation of its value before submitting it on the server side application. Let us look at a simple example on how to accomplish this using Javascript.

  <html>
    <head>
      <title>
        Javascript Validate HTML TextField
      </title>
      <script type="text/javascript">
        function validateTextBox() {
          var textBox1Value 
            = document.getElementById('textBox1').value;
          if(textBox1Value == null || textBox1Value == ''){
            alert('textBox1 is empty');
          } else {
            alert(textBox1Value);
          }
        }
      </script>
    </head>
    <body>
      <form>
        Text Here : 
        <input type='text' id='textBox1' name='textBox1' 
          value='' maxlength='100' /><br/>
        <input type='button' value='validate' 
          onclick='validateTextBox();' /><br/>
      </form>
    </body>
  </html>
                           
The example above is the most common way of validating an HTML textfield. It is usually done upon clicking the button that is supposed to submit the form to the server application. If the textfield or textbox is representing a data that is supposed to be mandatory, we will perform this kind of validation and stop the HTML form from being submitted to the backend application. The 'maxlength' attribute is for limiting the number of characters the user is able to supply or key in inside the text object. Let us look at another example.

  <html>
    <head>
      <title>
        Javascript Validate HTML TextField
      </title>
      <script type="text/javascript">
        function validateTextBox() {
          var textBox1Value 
            = document.getElementById('textBox1').value;
          alert('The character length is ' 
            + textBox1Value.length);
        }
      </script>
    </head>
    <body>
      <form>
        Text Here : 
        <input type='text' id='textBox1' name='textBox1' 
          value='' maxlength='100' 
          onkeyup='validateTextBox();' /><br/>
      </form>
    </body>
  </html>
                           
The above example demostrates how to use the Javascript 'onkeyup' event listener that can be used in textfields. You can also play around and replace the 'onkeyup' with 'onkeydown' or 'onkeypress'. See for yourself what are the slight difference on these events.

In this tutorial, we have seen how to use Javascript in performing validation on the HTML textfield.


Back    Next