Open Source Tutorials - Open Source Training
Open source training & tutorials from experienced, passionate people
chrome icon firefox icon ie icon opera icon safari icon Sings in these Browsers
A- A A+

By A Web Design

pdf icons text icons

Check that numbers and special characters are not inserted into a Textbox

Introduction:

In this example we are checking to see that the data entered into the username form field is only characters, numeric values or spaces. The username form field must not accept any other special characters.

This example displays a form that requires a Username to accept only characters, numeric values or spaces before its content are dispatched to a Web server for further processing. The look and feel of the form is as shown in diagram 1.

diagram1.gif
Diagram1

The first snippet of code described is the HTML responsible for rendering the form in the visitor’s browser as shown in diagram 1.

If Username contains special characters other than the ones permitted and the Submit button is clicked an Alert with an appropriate error message will be displayed as shown in diagram 2.

diagram2.gif
Diagram2

HTML Code snippet

 
<form name="frmTest" id="frmTest" method="post" action=""
onsubmit="return validateTest(document.frmTest);">
  <table id="tblTest" width="50%">
    <tr>
      <td align="right">Username</td>
      <td><input type="text" name="txtUsername" id="txtUsername" 
      value="" title="Username" /></td>
    </tr>
    <tr colspan="2" style="padding-left:160px;">
      <td>
        <input type="submit" name="btnSubmit" id="btnSubmit" 
        value="Submit" />
        <input type="reset" name="btnCancel" id="btnCancel" 
        value="Cancel" />
      </td>
    </tr>
  </table>
</form>
 

Elements used in the HTML code snippet are:

  1. Form
  2. Textbox
  3. Button

Description of each element

  1. Form: A form object is defined in HTML between the <FORM></FORM> tags. The form object will normally enclose holds various data capture HTML elements like Textboxes, Textareas, Combo-boxes, Radio buttons, Checkboxes and so on
  2. Textbox: It’s one of the many HTML data capture elements. It is used to capture text based, user data
  3. Button: A button is considered an HTML data control element. It’s usually used to perform some sort of controlling action such as submitting the form data captured to a Web server for further processing, resetting the form data to datum and so on.

In the form frmTest the Javascript function validateTest(document.frmTest) is called when the Submit button is clicked. This is how that happens:

When the Submit button is clicked, the frmTest onsubmit method is automatically invoked which in turn invokes the Javascript function validateTest(); The form is passed to this Javascript function as the parameter - document.frmTest. Hence the function validateTest(); operates on document.frmTest.

It’s the signature of validateTest(); that tests if txtUsername is left empty or not.

JAVASCRIPT Code Snippet

 
<script type="text/javascript">
function validateTest(objFrm)
{
var regex = 
/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/ ;
  //regex variable
  if(objFrm.txtUsername.value=="")
  //checking if the textbox txtUsername is empty
  {
    alert("Username cannot be left blank");
    //An alert box is popped up in the browser if it is 
    //with a message in it
    objFrm.txtUsername.focus();
    //Once the user responds to the alert the cursor is 
    //placed in the textbox again
    return false;
    //The value false is returned to the function so that 
    //form submission
  }
  else if(!regex.test(objFrm.txtUsername.value))
  {
    alert("Username can only contain alphabets, numbers 
    and spaces . Please provide valid Username");
    // An alert box is popped up in the browser if it is 
    //with a message in it
    objFrm.txtUsername.focus();
    //Once the user responds to the alert the cursor is 
    //placed in the textbox again
    return false;
    //The value false is returned to the function so that 
    //form submission
  }
  else
  {
    return true;
  }
}
</script>
 

NOTE: While Javascript code can be included anywhere in the HTML codespec it is prudent that Javascript is always written within the <HEAD></HEAD> HTML tags.

To separate Javascript code from HTML code it is always placed within the <script></script> that are normally placed within <HEAD></HEAD> HTML tags.

The <SCRIPT> tag has following attributes:
type: It specifies MIME type of script
src: Specifies the URL of an external Javascript file if one is used

Working of the Javascript code:

  1. The Javascript code is contained in the function validateTest(); This is passed the HTML form id frmTest as its argument
  2. objForm is the handle to HTML form object. It is a collection of HTML elements that are enclosed within the <FORM></FORM> tags. Using the handle objFrm all the elements within frmTest can be accessed
  3. Create a regular expression rule for not accepting special characterers

var regex = /^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/ ;

  • 1. Testing if objFrm.txtUsername.value is empty or not

if(objFrm.txtUsername.value=="")

  • 2. If it is empty then an Alert is popped up to catch the users attention and display an appropriate error message for the user to read

alert("Username cannot be left blank");

  • 3. Since an Alert is a modal window all processing will stop until the User responds to the Alert by clicking on the Alert’s Ok button
  • Then objFrm.txtUsername.focus(); places the form cursor back on the txtUsername HTML element

objFrm.txtUsername.focus();

  • 4. If objFrm.txtUsername is not empty (i.e. txtUsername contains something), then control will pass to else if block of the if condition. This will checks for special characters using regular expression and using javascript method test().if test method returns true then username is considered as valid and if test() method returns false (if input from user contains character like @,#,$,% etc.) then control stays in else if block only.

else if(!regex.test(objFrm.txtUsername.value))

  • 5. It leads to trigger an Alert to popped and it will catch the users attention and display an appropriate error message for the user to read

alert("Username can only contain alphabets, numbers and spaces. Please provide valid Username ");

  • 6. If it is empty then an Alert is popped up to catch the users attention and display an appropriate error message for the user to read
  • 7. If all conditions are valid (i.e. not empty and only alpha numeric values and/or space ), then control will pass to else block of the else if condition. This will return the value TRUE to the onsubmit method of the form object and the form’s contents will get submitted to the Web server for further processing.

NOTE: In this specific case nothing else will happen because the form’s ACTION attribute is loaded with the # symbol. Normally value passed to the ACTION attribute of the form is the name of the program at the Web server that will process the data submitted by the form to the Web server. In this case since the ACTION attribute holds # the Web server will receive the data submitted by the form by will do nothing further.

The Complete Code Snippet

 
<html>
  <head>
  <title>Username not contains special characters</title>
<script type="text/javascript">
function validateTest(objFrm)
{
var regex =
/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/;
  //regex variable
  if(objFrm.txtUsername.value=="")
  //checking if the textbox txtUsername is empty
  {
    alert("Username cannot be left blank");
    // An alert box is popped up in the browser if it is with 
    //a message in it
    objFrm.txtUsername.focus();
    //Once the user responds to the alert the cursor is placed 
    //in the textbox again
    return false;
    //The value false is returned to the function so that form 
    //submission
  }
  else if(!regex.test(objFrm.txtUsername.value))
  {
    alert("Username can only contain alphabets, numbers and spaces .
    Please provide valid Username");
    // An alert box is popped up in the browser if it is with 
    //a message in it
    objFrm.txtUsername.focus();
    //Once the user responds to the alert the cursor is placed 
    //in the textbox again
    return false;
    //The value false is returned to the function so that form 
    //submission
  }
  else
  {
    return true;
  }
}
</script>
</head>
 
<body>
<form name="frmTest" id="frmTest" method="post" action=""
onsubmit="return validateTest(document.frmTest);">
  <table id="tblTest" width="50%">
    <tr>
      <td align="right">Username</td>
      <td>
      <input type="text" name="txtUsername" id="txtUsername" 
      value="" title="Username" />
      </td>
    </tr>
    <tr>
      <td colspan="2" style="padding-left:160px;">
      <input type="submit" name="btnSubmit" id="btnSubmit" 
      value="Submit" />
      <input type="reset" name="btnCancel" id="btnCancel" 
      value="Cancel" />
      </td>
    </tr>
  </table>
</form>
</body>
</html>
 
OSV Newsletter


Receive HTML?

NOTE: To prevent subscription to the OSV newsletter, uncheck the checkbox above.
Guest Blog for OSV
Free Ebook Download
LinkShare_180x150
Artisteer - DNN Skin Generator
Tapestry Theme - A Tumblog-Style Theme for Wordpress