HOME | FERGUSON Digital Blog

Numeric Only Form Field

General Topics Add comments

To lock an input form field on the client side to only allow numeric entries, you can use a short piece of JavaScript that will limit the keys pressed. For example, a form field that is intended to record a monetary value, but the user types letters, dollar signs, commas etc. If you do not sanitize these entries before attempting to update your datasource, the page will error.

The first function limits what can actually be typed into the form field using "0123456789." as the key. Just add a minus sign to allow the recording of financial deficits "0123456789.-". This string can be modified in any way you wish to limit the input of a specific form field.

Just because you prevent them from typing spurious characters into your form field, does not mean the user will not be able to paste them from their buffer. The next two functions will lock the input so that the right mouse will not function. The second prevents the contextual menu from appearing and allowing the user to paste directly into the form field. The third prevents the CTRL key which in combination with the V keyboard key would allow the user to also paste directly into the form field.

<script type="text/javascript">
   fnNumberOnly=function(myfield, e) {
      var key;
      var keychar;
      if (window.event)
         key=window.event.keyCode;
      else if (e)
         key=e.which;
      else
         return true;
      keychar=String.fromCharCode(key);
      if ((key==null)||(key==0)||(key==8)||(key==9)||(key==13)||(key==27))
         return true;
      else if ((("0123456789.").indexOf(keychar) > -1))
         return true;
      else
         return false;}

   fnNoRightMouse=function(event) {
      if (event.button==2) {
         alert("RIGHT-CLICK is disabled for this field.   ");}}

   fnNoCTRL=function(e) {
      var code=(document.all) ? event.keyCode:e.which;
      var msg="'CTRL' key is disabled for this field.   ";
      if (parseInt(code)==17) {
         alert(msg);
         window.event.returnValue=false;}}
</script>


Usage:

<input name="TextBox" type="text" onKeyPress="return fnNumberOnly(this, event)" onmousedown="fnNoRightMouse(event)" onkeydown="return fnNoCTRL(event)" />

If you find this post useful please leave a comment and let me know how you used the information.

0 responses to “Numeric Only Form Field”

Leave a Reply




© Copyright 1997-2024, All Rights Reserved Coldfusion and MS SQL2008
Powered by Mango Blog.   Design by FERGUSON Digital
o:Event name="beforeHtmlBodyEnd" />