help with RegEx

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

    help with RegEx

    hello,

    i need a regular expression for my form-validation:

    it should be allowed to fill a <input type="text"with

    any iteger number up to 500
    or
    a integer number up to 500 followed by px (e.g. "200px")
    or
    a integer number up to 85 followed by % (e.g. "45%")

    anything else should be returned false with a alert-message.
    i'm not good in RegEx and i didn't find a example for that online.
    maybe someone here can help me?

    thanks a lot,
    Martin Nadoll


  • Bjoern Hoehrmann

    #2
    Re: help with RegEx

    * Martin Nadoll wrote in comp.lang.javas cript:
    >i need a regular expression for my form-validation:
    >
    >it should be allowed to fill a <input type="text"with
    >
    >any iteger number up to 500
    >or
    >a integer number up to 500 followed by px (e.g. "200px")
    >or
    >a integer number up to 85 followed by % (e.g. "45%")
    >
    >anything else should be returned false with a alert-message.
    >i'm not good in RegEx and i didn't find a example for that online.
    >maybe someone here can help me?
    Unless you absolutely have to use a regular expression, this is best
    done by converting the strings to a suitable number and check that
    instead. A regex would look like

    * 500 optionally followed by px, or
    * 4 or 3 or 2 or 1 optionally followed
    by 1 or 2 digits optionally followed by px, or
    * ...

    Which isn't particularily pretty in comparison (think about how to
    change or proof-read it in the future).
    --
    Björn Höhrmann · mailto:bjoern@h oehrmann.de · http://bjoern.hoehrmann.de
    Weinh. Str. 22 · Telefon: +49(0)621/4309674 · http://www.bjoernsworld.de
    68309 Mannheim · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/

    Comment

    • VK

      #3
      Re: help with RegEx

      On Apr 26, 8:00 pm, "Martin Nadoll" <mar...@nadoll. dewrote:
      hello,
      >
      i need a regular expression for my form-validation:
      >
      it should be allowed to fill a <input type="text"with
      >
      any iteger number up to 500
      or
      a integer number up to 500 followed by px (e.g. "200px")
      or
      a integer number up to 85 followed by % (e.g. "45%")
      >
      anything else should be returned false with a alert-message.
      i'm not good in RegEx and i didn't find a example for that online.
      In such case maybe it is better to use straightforward if-else check
      instead. The code you can understand is much easier to maintain and to
      update plus much lesser risk of occasional typos.


      n = document.forms['MyForm'].MyElement.valu e;

      if ((+n < 0) || (parseInt(n) != +n)) {
      return false;
      }
      if ((n.lastIndexOf ('%') != -1) && (+n <= 85)) {
      return true;
      }
      else if ((n.lastIndexOf ('%') == -1) && (+n <= 500)) {
      return true;
      }
      else {
      return false;
      }

      Comment

      • Evertjan.

        #4
        Re: help with RegEx

        Martin Nadoll wrote on 26 apr 2008 in comp.lang.javas cript:
        hello,
        >
        i need a regular expression for my form-validation:
        >
        it should be allowed to fill a <input type="text"with
        >
        any iteger number up to 500
        or
        a integer number up to 500 followed by px (e.g. "200px")
        or
        a integer number up to 85 followed by % (e.g. "45%")
        >
        anything else should be returned false with a alert-message.
        i'm not good in RegEx and i didn't find a example for that online.
        maybe someone here can help me?
        <script type='text/javascript'>

        var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^( ((8[0-5])|([1-7]\d)|[1-
        9])\%)$/;

        function testMe(f){
        if (re.test(f.elem ents['myField'].value))
        return true;
        alert('Somethin g rotten in myField');
        return false;
        };

        </script>

        <form onsubmit='retur n testMe(this)'>
        <input type="text" name='myField'>
        </form>

        =============== ======

        It seems that the present mood is, that because Regex is unreadable for a
        later moronic reviewer of your code, so should not be used.
        I do not agree.
        Perhaps the exploded view below provides additional explanation:

        ^
        (
        (
        (500)|
        ([1-4]\d\d)|
        ([1-9]\d?)
        )
        (px)?
        )
        $
        |
        ^
        (
        (
        (8[0-5])|
        ([1-7]\d)|
        [1-9]
        )
        \%
        )
        $



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

        Comment

        • Dr J R Stockton

          #5
          Re: help with RegEx

          In comp.lang.javas cript message <48135181$0$676 9$9b4e6d93@news spool2.arc
          or-online.net>, Sat, 26 Apr 2008 18:00:05, Martin Nadoll
          <martin@nadoll. deposted:
          >hello,
          >
          >i need a regular expression for my form-validation:
          >
          >it should be allowed to fill a <input type="text"with
          >
          >any iteger number up to 500
          >or
          >a integer number up to 500 followed by px (e.g. "200px")
          >or
          >a integer number up to 85 followed by % (e.g. "45%")
          >
          >anything else should be returned false with a alert-message.
          >i'm not good in RegEx and i didn't find a example for that online.
          >maybe someone here can help me?
          The best way is to RegExp-match the general pattern, of digits followed
          optionally by px or %, followed by specific-to-case code. The .match
          combines matching pattern, splitting into fields, ensuring non-negative.

          Would 0240px be allowed? it fits your description.

          Consider and test

          var U

          Num = Str = Max = U

          Pattern = VALUE.match(/^(\d+)(%|px)?$/)
          if (Pattern) {
          Num = +Pattern[1] ; Str = Pattern[2]
          Max = Str=="%" ? 85 : 500 }

          A = [ !!Pattern, Max, Num, Str, Num<=Max ]

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

          --
          (c) John Stockton, nr London UK. ?@merlyn.demon. co.uk IE7 FF2 Op9 Sf3
          news:comp.lang. javascript FAQ <URL:http://www.jibbering.c om/faq/index.html>.
          <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

          • Lasse Reichstein Nielsen

            #6
            Re: help with RegEx

            "Evertjan." <exjxw.hannivoo rt@interxnl.net writes:
            var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^( ((8[0-5])|([1-7]\d)|[1-
            9])\%)$/;
            Good example of why not to use RegExp's for numerical comparison :)
            It's almost unreadable, and it still doesn't match 0px (although that
            could be by design).

            function testMe(f) {
            var match = f.match(/^(\d+)(px|%)?$/);
            if (!match) { return false; }
            var num = +match[1];
            switch(match[2]) {
            case '%': return num <= 85;
            case 'px':
            default:
            return num <= 500;
            }
            }
            It seems that the present mood is, that because Regex is unreadable for a
            later moronic reviewer of your code, so should not be used.
            Not hard to read, but hard to modify too, although that is related.
            I do not agree.
            I do. Making code maintainable is important, to later "moronic
            reviewers" (aka, your esteemed collegues and yourself in 30 days).

            Try changing the limit from 85 to 125, and consider how many places
            you need to change. Maintainable code should only need to change in
            one place, where "85" is replaced by "125".

            For added credit, I should have created them as constants instead
            of inlined literals.

            /L
            --
            Lasse Reichstein Nielsen - lrn@hotpop.com
            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Evertjan.

              #7
              Re: help with RegEx

              Lasse Reichstein Nielsen wrote on 27 apr 2008 in comp.lang.javas cript:
              "Evertjan." <exjxw.hannivoo rt@interxnl.net writes:
              >
              >var
              >re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^( ((8[0-5])|([1-7]\d)|[1-
              >9])\%)$/;
              >
              Good example of why not to use RegExp's for numerical comparison :)
              It's almost unreadable, and it still doesn't match 0px (although that
              could be by design).
              Tast was my design, it would be simpler without restricting the zero.

              re=/^(((500)|([1-4]\d\d)|([1-9]?\d))(px)?)$|^( ((8[0-5])|([1-7]?\d))\%)$/;

              function testMe(f) {
              var match = f.match(/^(\d+)(px|%)?$/);
              if (!match) { return false; }
              var num = +match[1];
              switch(match[2]) {
              case '%': return num <= 85;
              case 'px':
              default:
              return num <= 500;
              }
              >}
              >
              >It seems that the present mood is, that because Regex is unreadable
              >for a later moronic reviewer of your code, so should not be used.
              >
              Not hard to read, but hard to modify too, although that is related.
              >
              >I do not agree.
              >
              I do. Making code maintainable is important, to later "moronic
              reviewers" (aka, your esteemed collegues and yourself in 30 days).
              No, it is only important in your environment, but not in mine.

              I, and many others I surmize, code for personal joy, compactness and
              elegance, and mastering the Regex is a joy in itself.

              I could not care less, if my code is unreadable if I am not around.
              Throw it away, throw it away, throw it away!

              After a few years I love to start from scratch and incorporate all the
              new methods I learned or developed to get the same result perhaps in a
              more elegant way.
              Try changing the limit from 85 to 125, and consider how many places
              you need to change. Maintainable code should only need to change in
              one place, where "85" is replaced by "125".
              Ah, an added challenge, I would like that.

              OK, warn for lack of maintainability ,
              but don't dismiss the pleasure of such coding per se.

              In my assembler days, each line had one or more comment lines to make it
              readable, but those days are gone. Dreadfull sorry, Clementine? Perhaps.

              However I am not even against the Javascript equivalents of the ancient
              BASIC left(), mid(), right() and the less old instr(). With a lot of
              code, you can get the same results.

              3 or 4 years ago I could not "do" regex, and I didn't miss it, but you
              never miss what you do not know.

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

              Comment

              • Dr J R Stockton

                #8
                Re: help with RegEx

                In comp.lang.javas cript message <Xns9A8CD75609E 7eejj99@194.109 .133.242>,
                Sat, 26 Apr 2008 19:10:11, Evertjan. <exjxw.hannivoo rt@interxnl.net >
                posted:
                >
                >var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^( ((8[0-5])|([1-7]\d)|[1-
                >9])\%)$/;
                Rejects zero, which the OP's wording did not call for.

                --
                (c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
                Web <URL:http://www.merlyn.demo n.co.uk/- FAQqish topics, acronyms & links;
                Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
                No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.

                Comment

                • Evertjan.

                  #9
                  Re: help with RegEx

                  Dr J R Stockton wrote on 27 apr 2008 in comp.lang.javas cript:
                  In comp.lang.javas cript message <Xns9A8CD75609E 7eejj99@194.109 .133.242>,
                  Sat, 26 Apr 2008 19:10:11, Evertjan. <exjxw.hannivoo rt@interxnl.net >
                  posted:
                  >>
                  >>var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^( ((8[0-5])|([1-7]\d)|[1-
                  >>9])\%)$/;
                  >
                  Rejects zero, which the OP's wording did not call for.
                  >
                  Methinks that is implicit, but the alternative was already posted:

                  re=/^(((500)|([1-4]\d\d)|([1-9]?\d))(px)?)$|^( ((8[0-5])|([1-7]?\d))\%)$/;


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

                  Comment

                  Working...