Typing filtering (JS)

On 9-21-2005, in Coding, JavaScript, by Alex

Do you have the field for numbers only?

My special JS function has been created to restrict the typing by regExp pattern:

JavaScript:


var isIE4up = (document.all) ? 1 : 0;
var isIE5 = (isIE4up && navigator.appVersion.indexOf("MSIE 5") != -1) ? 1 : 0;
var isIE6 = (isIE4up && navigator.appVersion.indexOf("MSIE 6") != -1) ? 1 : 0;

function keyFilter(e, strPattern) {
// (c) Mauzon :)
  var chr = (isIE4up || isIE6 || isIE6)?e.keyCode:e.which;
  var ch = String.fromCharCode(chr);
    if (chr != 13 && chr !=  8 ) {
    var re = new RegExp(strPattern);
    if (ch.search(re) == -1) {
      if(isIE4up || isIE6 || isIE6){
       e.returnValue = false;
      }else{
       e.preventDefault();
      }
    }
  }
}

(x)HTML:


<input type="text" onkeypress="keyFilterA(event,'[0-9]')" /> lets visitor to add Integers only;
<input type="text" onkeypress="keyFilterA(event,'[0-9\.\,]')" /> numbers with decimal delimiter;
<input type="text" onkeypress="keyFilterA(event,'[a-zA-Z]')" /> letters;

PS. Special thanks for Anton Zinevic aka Buka 4 help

 

3 Responses to Typing filtering (JS)

  1. CB says:

    Hello!
    Tnx for a good script. But I think that it can be improved. Here is my version:
    var isIE = (document.all) ? 1 : 0;

    function keyFilter(e, strPattern)
    {
    // (c) Mauzon :) , modified by CB
    var chr = (isIE) ? e.keyCode : e.which;
    var ch = String.fromCharCode(chr);

    if (chr != 13 && chr != 8 && chr != 0)
    {
    var re = new RegExp(strPattern);

    if (ch.search(re) == -1)
    {
    if(isIE)
    e.returnValue = false;
    else
    e.preventDefault();
    }
    }
    }

  2. CB says:

    I added for example && chr != 0 for processing such keys as F5 and so on.

    Also I think that
    var isIE = (document.all) ? 1 : 0;
    is enough for correct work.

  3. Alex says:

    Great!
    Thank you very much :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>