RegExp for delete, backspace and arrow keys

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Laphan

    RegExp for delete, backspace and arrow keys

    Hi All

    I'm using the below to limit the input into a text box to just letters,
    numbers, hyphens and full stops, but I also need to allow the backspace,
    delete and arrow keys to come through. How can I do this?

    <script language="JavaS cript" type="text/javascript">
    <!--
    function onKeyPressBlock Numbers(e)
    {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromChar Code(key);
    reg = /^[.a-zA-Z0-9_-]*$/;
    return reg.test(keycha r);
    }
    //-->
    </script>

    <form>
    <input type="text" onkeypress="ret urn onKeyPressBlock Numbers(event); " />
    </form>

    Thanks

    Laphan


  • Stephen Chalmers

    #2
    Re: RegExp for delete, backspace and arrow keys


    Laphan wrote:
    Hi All
    >
    I'm using the below to limit the input into a text box to just letters,
    numbers, hyphens and full stops, but I also need to allow the backspace,
    delete and arrow keys to come through. How can I do this?
    >
    >
    <form>
    <input type="text"
    onkeyup='this.v alue=this.value .replace(/[^\.A-Z0-9_-]/ig,"")' />
    </form>

    Comment

    • RobG

      #3
      Re: RegExp for delete, backspace and arrow keys


      Laphan wrote:
      Hi All
      >
      I'm using the below to limit the input into a text box to just letters,
      numbers, hyphens and full stops, but I also need to allow the backspace,
      delete and arrow keys to come through. How can I do this?
      >
      <script language="JavaS cript" type="text/javascript">
      The language attribute is deprecated, remove it. Keep type.
      <!--
      Don't use HTML comment delimiters inside script elements.

      function onKeyPressBlock Numbers(e)
      {
      var key = window.event ? e.keyCode : e.which;
      Stephen has already given you the real answer, but for the record, if
      you want to use feature detection (and that is good) you should base it
      on the feature you are trying to detect support for, not some unrelated
      feature. Rather than inferring support for keyCode or which based on
      window.event, use the actual property:

      var key = e.keyCode || e.which;

      var keychar = String.fromChar Code(key);
      reg = /^[.a-zA-Z0-9_-]*$/;
      Since you are only testing a single character, the special characters
      ^, $ and * are probably redundant (but harmless).
      return reg.test(keycha r);
      Consider:

      return /[\w-.]/.test(keychar);

      The use of key events to filter input doesn't work reliably because you
      can enter data without registering any key events and the keys pressed
      may not correlate with the interpreted key character or the data
      entered (e.g. ctrl + v).

      --
      Rob

      Comment

      • GreyWyvern

        #4
        Re: RegExp for delete, backspace and arrow keys

        And lo, Laphan didst speak in alt.www.webmaster,comp.lang.javascript:
        Hi All
        >
        I'm using the below to limit the input into a text box to just letters,
        numbers, hyphens and full stops, but I also need to allow the backspace,
        delete and arrow keys to come through. How can I do this?
        >
        <script language="JavaS cript" type="text/javascript">
        <!--
        function onKeyPressBlock Numbers(e)
        {
        var key = window.event ? e.keyCode : e.which;
        var keychar = String.fromChar Code(key);
        reg = /^[.a-zA-Z0-9_-]*$/;
        return reg.test(keycha r);
        }
        //-->
        </script>
        First, don't use the onkeypress event. onkeypress differs from
        onkeydown/onkeyup in that the code it returns is mostly limited to the
        ASCII set and a few special keys.

        In contrast, onkeyup and onkeydown return codes which report almost every
        key on the keyboard, from the letter A to the F1-F12 function keys. This
        is made possible mostly due to discarding the lowercase letter range of
        the ASCII set and using these values for various special keys. Because of
        this, you cannot determine whether a letter entered is uppercase or
        lowercase quite so easily, but usually this isn't a problem. I recommend
        using the onkeydown event.

        Second, don't use a regexp at all. Instead filter the input directly from
        the keyCode.

        Here are the relevant keyCodes you want:

        Letters = 65 - 90
        Numbers = 48 - 57
        Hyphen = 189
        Full Stop = 190
        Backspace = 8
        Delete = 46
        Arrow Keys = 37 - 40

        If the keyCode recieved does not match anything in those ranges, simply
        disallow the event. Keep in mind that this security is worthless if JS is
        disabled so be sure to do full checking server-side also.

        Grey

        --
        The technical axiom that nothing is impossible sinisterly implies the
        pitfall corollary that nothing is ridiculous.
        - http://www.greywyvern.com/orca#search - Orca Search: Full-featured
        spider and site-search engine

        Comment

        • Laphan

          #5
          Re: RegExp for delete, backspace and arrow keys

          Hi Guys

          Many thanks for your valued help.

          I didn't manage to see these posts until today, so the method I'm currently
          using is:

          function CheckCodeEntry( e) {

          var key = window.event ? e.keyCode : e.which;

          if (e.shiftKey==1) {

          if (key == 8 || key == 9 ||
          key == 46 || (key 36 && key < 41) ||
          (key 63 && key < 74) || (key 64 && key < 91) ||
          key == 189) {
          return true;
          }
          else {
          return false;
          }

          }
          else {

          if (key == 8 || key == 9 || key == 190 ||
          key == 46 || (key 36 && key < 41) ||
          (key 47 && key < 58) || (key 64 && key < 91) ||
          (key 95 && key < 106) || key == 189) {
          return true;
          }
          else {
          return false;
          }

          }

          }

          JS in input box is onKeyDown='retu rn CheckCodeEntry( event)'
          onKeydown='retu rn CheckCodeEntry( event)'

          Can you see any issues with this? Appears to work OK in IE and FireFox.

          Please note that I only use this code as a helping hand to the user at the
          point of entry. I also check on submitting the form (JS) and server side
          (ASP).

          Thanks

          Laphan

          "GreyWyvern " <spam@greywyver n.comwrote in message
          news:op.tiq6rfb 3sl6xfd@news.na s.net...
          And lo, Laphan didst speak in alt.www.webmaster,comp.lang.javascript:
          Hi All
          >
          I'm using the below to limit the input into a text box to just letters,
          numbers, hyphens and full stops, but I also need to allow the backspace,
          delete and arrow keys to come through. How can I do this?
          >
          <script language="JavaS cript" type="text/javascript">
          <!--
          function onKeyPressBlock Numbers(e)
          {
          var key = window.event ? e.keyCode : e.which;
          var keychar = String.fromChar Code(key);
          reg = /^[.a-zA-Z0-9_-]*$/;
          return reg.test(keycha r);
          }
          //-->
          </script>
          First, don't use the onkeypress event. onkeypress differs from
          onkeydown/onkeyup in that the code it returns is mostly limited to the
          ASCII set and a few special keys.

          In contrast, onkeyup and onkeydown return codes which report almost every
          key on the keyboard, from the letter A to the F1-F12 function keys. This
          is made possible mostly due to discarding the lowercase letter range of
          the ASCII set and using these values for various special keys. Because of
          this, you cannot determine whether a letter entered is uppercase or
          lowercase quite so easily, but usually this isn't a problem. I recommend
          using the onkeydown event.

          Second, don't use a regexp at all. Instead filter the input directly from
          the keyCode.

          Here are the relevant keyCodes you want:

          Letters = 65 - 90
          Numbers = 48 - 57
          Hyphen = 189
          Full Stop = 190
          Backspace = 8
          Delete = 46
          Arrow Keys = 37 - 40

          If the keyCode recieved does not match anything in those ranges, simply
          disallow the event. Keep in mind that this security is worthless if JS is
          disabled so be sure to do full checking server-side also.

          Grey

          --
          The technical axiom that nothing is impossible sinisterly implies the
          pitfall corollary that nothing is ridiculous.
          - http://www.greywyvern.com/orca#search - Orca Search: Full-featured
          spider and site-search engine


          Comment

          • RobG

            #6
            Re: RegExp for delete, backspace and arrow keys

            Laphan wrote:
            Hi Guys
            >
            Many thanks for your valued help.
            Please don't top-post, reply below trimmed quotes.

            I didn't manage to see these posts until today, so the method I'm currently
            using is:
            >
            function CheckCodeEntry( e) {
            >
            var key = window.event ? e.keyCode : e.which;
            Which is still based on erroneous feature detection, do you know
            whether all browsers that don't support window.event *will* support
            event.which?

            Feature detection should be based on the feature you are actually
            trying to detect support for:

            var key = e.keyCode || e.which;
            if (typeof key != 'number') return;

            if (e.shiftKey==1) {
            What about the control key? Or other modifiers - Windows key, Apple
            key, special function keys... ?


            [...]
            >
            JS in input box is onKeyDown='retu rn CheckCodeEntry( event)'
            onKeydown='retu rn CheckCodeEntry( event)'
            >
            Can you see any issues with this?
            Other than the duplicate attribute? I guess that's a typo :-)

            It will not check data that is input from events you don't check for
            (paste using ctrl+v, right mouse button or edit menu, autofill) and it
            is considerably longer and less reliable than the previously suggested
            regular expression method.
            Appears to work OK in IE and FireFox.
            For those browsers on Windows perhaps, but it is inconsistent in other
            browsers and on other platforms.
            Please note that I only use this code as a helping hand to the user at the
            point of entry. I also check on submitting the form (JS) and server side
            (ASP).
            Which means that the best method would be to use a regular expression
            to test the field value onsubmit, the benefits being that you:

            1. Can (very likely) use the same RegExp on the server as on the
            client.

            2. Can do the same validation on key events and onsubmit

            3. Don't care how the user gets the data into the input

            4. Aren't concerned about any special features that their browser may
            have in regard to keyCode values or data input.

            Try the following example:

            <script type="text/javascript">

            function validate(el){
            var errorEl = document.getEle mentById(el.nam e + '_err');
            var errorMsg = '';
            if (/[^\w-.]/.test(el.value) ){
            errorMsg = 'Only letters, digits, hyphen (-)'
            + ' and period (.) allowed';
            }
            if (errorEl){
            errorEl.innerHT ML = errorMsg;
            }
            return (errorMsg == '');
            }

            </script>
            <form action="" onsubmit="retur n validate(this.t extA);">
            <input type="text" name="textA" onkeyup="valida te(this);">
            <span id="textA_err" style="font-weight:bold;"></span><br>
            <input type="submit">
            </form>


            --
            Rob

            Comment

            • Dr J R Stockton

              #7
              Re: RegExp for delete, backspace and arrow keys

              In message <12l73jvci5if33 6@corp.supernew s.com>, Thu, 9 Nov 2006
              20:24:18, Laphan <info@PleaseDon tSpam.comwrites
              >
              >function CheckCodeEntry( e) {
              >
              >var key = window.event ? e.keyCode : e.which;
              >
              >if (e.shiftKey==1) {
              >
              if (key == 8 || key == 9 ||
              key == 46 || (key 36 && key < 41) ||
              (key 63 && key < 74) || (key 64 && key < 91) ||
              key == 189) {
              return true;
              }
              else {
              return false;
              }
              >
              >}
              >else {
              >
              if (key == 8 || key == 9 || key == 190 ||
              key == 46 || (key 36 && key < 41) ||
              (key 47 && key < 58) || (key 64 && key < 91) ||
              (key 95 && key < 106) || key == 189) {
              return true;
              }
              else {
              return false;
              }
              >
              >}
              >
              >}

              Statements like "if (X) return true else return false" should be written
              as "return X". After a "return" there's no need for an "else".

              Most combinations of 'key' are used independently of the 'shiftKey'
              state, so extract them, getting something like :

              if (key == 8 || key == 9 || ... key == 189) return true

              if (e.shiftKey==1) return (key 63 && key < 74) || (key 64 && key <
              91)

              return (key 47 && key < 58) || (key 64 && key < 91) || (key 95 &&
              key < 106)


              The numbers for the shifted case look suspect.

              It's a good idea to read the newsgroup and its FAQ. See below.

              --
              (c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6
              <URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
              <URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              • Laphan

                #8
                Re: RegExp for delete, backspace and arrow keys


                "Dr J R Stockton" <jrs@merlyn.dem on.co.ukwrote in message
                news:EGM3SHv0kI VFFwGE@invalid. uk.co.demon.mer lyn.invalid...
                In message <12l73jvci5if33 6@corp.supernew s.com>, Thu, 9 Nov 2006
                20:24:18, Laphan <info@PleaseDon tSpam.comwrites
                >
                >function CheckCodeEntry( e) {
                >
                >var key = window.event ? e.keyCode : e.which;
                >
                >if (e.shiftKey==1) {
                >
                if (key == 8 || key == 9 ||
                key == 46 || (key 36 && key < 41) ||
                (key 63 && key < 74) || (key 64 && key < 91) ||
                key == 189) {
                return true;
                }
                else {
                return false;
                }
                >
                >}
                >else {
                >
                if (key == 8 || key == 9 || key == 190 ||
                key == 46 || (key 36 && key < 41) ||
                (key 47 && key < 58) || (key 64 && key < 91) ||
                (key 95 && key < 106) || key == 189) {
                return true;
                }
                else {
                return false;
                }
                >
                >}
                >
                >}

                Statements like "if (X) return true else return false" should be written
                as "return X". After a "return" there's no need for an "else".

                Most combinations of 'key' are used independently of the 'shiftKey'
                state, so extract them, getting something like :

                if (key == 8 || key == 9 || ... key == 189) return true

                if (e.shiftKey==1) return (key 63 && key < 74) || (key 64 && key <
                91)

                return (key 47 && key < 58) || (key 64 && key < 91) || (key 95 &&
                key < 106)


                The numbers for the shifted case look suspect.

                It's a good idea to read the newsgroup and its FAQ. See below.

                --
                (c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE
                6
                <URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of
                news:comp.lang. javascript
                <URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates,
                sources.
                <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items,
                links.





                Many thanks guys


                Comment

                • Evertjan.

                  #9
                  Re: RegExp for delete, backspace and arrow keys

                  Laphan wrote on 11 nov 2006 in comp.lang.javas cript:
                  Statements like "if (X) return true else return false" should be written
                  as "return X". After a "return" there's no need for an "else".
                  >
                  Most combinations of 'key' are used independently of the 'shiftKey'
                  state, so extract them, getting something like :

                  function CheckCodeEntry( e) {

                  var key = window.event ? e.keyCode : e.which;

                  return key == 8
                  || key == 9
                  || (key 36 && key < 41)
                  || key == 46
                  || (key 63 && key < 74)
                  || (key 64 && key < 91)
                  || key == 189
                  || (e.shiftKey == 1)
                  && ( (key 47 && key < 58)
                  || (key 73 && key < 91)
                  || (key 95 && key < 106)
                  || key == 190
                  )

                  }
                  >
                  The numbers for the shifted case look suspect.
                  >

                  --
                  Evertjan.
                  The Netherlands.
                  (Please change the x'es to dots in my emailaddress)

                  Comment

                  • Evertjan.

                    #10
                    Re: RegExp for delete, backspace and arrow keys

                    Evertjan. wrote on 11 nov 2006 in comp.lang.javas cript:
                    function CheckCodeEntry( e) {
                    >
                    var key = window.event ? e.keyCode : e.which;
                    >
                    return key == 8
                    || key == 9
                    || (key 36 && key < 41)
                    || key == 46
                    || (key 63 && key < 74)
                    || (key 64 && key < 91)
                    || (key 63 && key < 91)
                    || key == 189
                    || (e.shiftKey == 1)
                    && ( (key 47 && key < 58)
                    || (key 73 && key < 91)
                    leave the above line out, already covered
                    || (key 95 && key < 106)
                    || key == 190
                    )
                    >
                    >}
                    >
                    Or something like this:

                    return /[\x08\x09\x25-\x28\x2E\x40-\x5A\xBD]/.test(key) ||
                    ((e.shiftKey==1 ) && /[\x30-\x39\x60-\x69\xBE]/.test(key))


                    --
                    Evertjan.
                    The Netherlands.
                    (Please change the x'es to dots in my emailaddress)

                    Comment

                    Working...