regEx in Javascript

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

    regEx in Javascript

    Hi,

    I'm new to javascript and regEx and trying to solve the following
    problem.

    I have a function which validates the password if there is a number:
    -------------------------------------------------
    function findNumeric(str _obj){
    regEx = /\d/;
    if (str_obj.match( regEx))
    return true;
    else
    return false;
    }
    --------------------------------------------------
    The problem arises when I put a password with a space in between e.g:
    'test test1'. The fucntion returns false. I've tried '\s' in the
    regEx but the user can put the space anywhere..

    Any idea how to solve this problem as I should be able to put any
    alplanumeric value into the password, including space.

    Thanks a lot.

    Vish
  • Vincent van Beveren

    #2
    Re: regEx in Javascript

    [color=blue]
    > Any idea how to solve this problem as I should be able to put any
    > alplanumeric value into the password, including space.
    >
    > Thanks a lot.
    >
    > Vish[/color]

    Maybe you should define it global:

    /\d/g


    Comment

    • PatD

      #3
      Re: regEx in Javascript

      In a land long ago, in a time far away
      vishantu@hotmai l.com (Vishant) wrote:
      [color=blue]
      >Hi,
      >
      >I'm new to javascript and regEx and trying to solve the following
      >problem.
      >
      >I have a function which validates the password if there is a number:
      >-------------------------------------------------
      >function findNumeric(str _obj){
      >regEx = /\d/;
      > if (str_obj.match( regEx))
      > return true;
      > else
      > return false;
      >}
      >--------------------------------------------------
      >The problem arises when I put a password with a space in between e.g:
      >'test test1'. The fucntion returns false. I've tried '\s' in the
      >regEx but the user can put the space anywhere..[/color]

      Others here might correct me, but I'm pretty sure that:
      function findNumeric(str _obj)
      {
      return str_obj.match(/\d/);
      }
      does exactly what you want, even with strange inputs like "test test1".

      You're sure the problem comes from the "space or no space"?


      --
      Yours
      P

      Comment

      • Evertjan.

        #4
        Re: regEx in Javascript

        Vishant wrote on 07 jun 2004 in comp.lang.javas cript:
        [color=blue]
        > function findNumeric(str _obj){
        > regEx = /\d/;
        > if (str_obj.match( regEx))
        > return true;
        > else
        > return false;
        >[/color]

        Use test()

        =======
        This returns true if at least 1 char is a number:

        function findNumeric(str _obj){
        return /\d/.test(str_obj)
        }

        =======
        This returns true if all chars are numbers,
        and the string is not empty:

        function findNumeric(str _obj){
        return /^\d+$/.test(str_obj)
        }

        =======
        This returns true if all chars are numbers or whitespace,
        and the string is not empty:

        function findNumeric(str _obj){
        return /^[\d\s]+$/.test(str_obj)
        }

        =======
        This returns true if all chars are numbers,
        starting and ending white space allowed,
        and the string is not empty:

        function findNumeric(str _obj){
        return /^\s*\d+\s*$/.test(str_obj)
        }

        not tested!

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

        Comment

        • Shawn Milo

          #5
          Re: regEx in Javascript

          Here is a function I wrote to validate passwords in Javascript.

          Rules:
          1. capital and lower-case letters
          2. at least one digit
          3. not the same as their user name
          4. not the same as the old password
          5. not blank
          6. minimum length
          7. at least one letter
          8. no white-space
          9. does not contain certain names


          There are a couple of things here that aren't best-practice,
          but I was required to tack this on to an existing
          web application, without the freedom to do much to
          the original form. I hope you find some of this
          to be helpful.


          To answer your original question, here is a quickie
          that may be helpful.

          function checkForDigit(s trTest){

          if (strTest.match(/\d/)){
          alert('\'' + strTest + '\' contains a digit');

          if (strTest.match(/^\d+$/)){
          alert('\'' + strTest + '\' is completely numeric.');
          }

          }else{
          alert('\'' + strTest + '\' does not contain a digit');
          }

          }

          checkForDigit(' nstaoheu');
          checkForDigit(' nst4oheu');
          checkForDigit(' a');
          checkForDigit(' 4');




          Shawn



          //password validation.js
          function validatePass(fo rmName, oldPass, newPass1, newPass2){
          //function written on September 18th, 2003
          //by Shawn Milochik (Milo LinuxMail Org)
          //
          //Revisions: none
          //

          //declare variables we will use
          var returnValue = true; //will decide whether or not to submit the
          form

          var strOldPass = eval('document. ' + formName + '.' + oldPass +
          '.value');
          var strNewPass1 = eval('document. ' + formName + '.' + newPass1 +
          '.value');
          var strNewPass2 = eval('document. ' + formName + '.' + newPass2 +
          '.value');
          var errMessage = '';


          //For testing, to show what was entered for the old
          //and new passwords
          //alert(strNewPas s1 + ', ' + strNewPass2);

          var minLength = 7; // change this to change the minimum password
          length
          var strUID = document.locati on + ''; //get the querystring from the
          browser so we can get the Uid

          //Time-limited test stuff
          //replace the actual querystring with the sample
          //pulled from the real page
          if (new Date('9/26/2003 15:00:00') > new Date()){
          alert('testing mode, using fake querystring');
          strUID = 'http://gebis/mstr7/ChangePassword. asp?Server=GDRD WEB01&Project=G EBIS+%28Product ion%29&ProjectI d=7FFAF9AC11D4F 601500083903038 D204&Port=0&Uid =dwuser&UMode=1 ';
          }




          //get the Uid from the querystring, and put it in strUID
          //of the Uid in the querystring.
          strUID = strUID.replace(/^.*\&Uid=(\w+)\ &.*$/, "$1");

          // Regular Expression translation for above:
          // ^ = beginning of the line
          // . = any character
          // * = any number of the preceeding value, including zero
          // \& = & (& is a special character, and needs to be
          escaped)
          // Uid = find the string "Uid"
          // \w = a word character (a-z, A-Z, 0-9, _)
          // + = one or more consecutive positions
          // \& = & (& is a special character, and needs to be
          escaped)
          // . = any character
          // * = any number of the preceeding value, including zero
          // $ = the end of the line
          //
          // Using parenthesis around part of the expression allows us
          to use
          // the matching text in the replace function. In this case,
          (\w+)
          // allowed us to return whatever \w+ matched as $1. If we
          had used
          // another set of parenthesis, we could refer to the second
          one as
          // $2, and so on.
          //
          //See "Mastering Regular Expressions" by Jeffrey Friedl for all
          this and more.
          //



          //*************** *************** *************** *************
          // Rule: Must contain both upper and lower case
          //*************** *************** *************** *************
          //Check for all lower-case
          if (strNewPass1.to LowerCase() == strNewPass1){
          //alert('New password must contain at least one upper-case
          character.');
          errMessage = errMessage + '\n' + 'New password must contain at
          least one upper-case character.';
          returnValue = false;
          }

          //Check for all upper-case
          if (strNewPass1.to UpperCase() == strNewPass1){
          //alert('New password must contain at least one lower-case
          character.');
          errMessage = errMessage + '\n' + 'New password must contain at
          least one lower-case character.';
          returnValue = false;
          }


          //*************** *************** *************** *************
          // Rule: password does not match the user name
          //*************** *************** *************** *************
          if (strNewPass1 == strUID){
          alert('New password may not be the same as your user ID.');
          returnValue = false;
          }


          //*************** *************** *************** *************
          // Rule: new password is the same in both password boxes
          //*************** *************** *************** *************
          if (strNewPass1 != strNewPass2){
          alert('New passwords do not match.');
          returnValue = false;
          }

          //*************** *************** *************** *************
          // Rule: password is not the same as the old
          //*************** *************** *************** *************
          if (strNewPass1 == strOldPass){
          alert('New passwords may not be the same as the old one.');
          returnValue = false;
          }


          //*************** *************** *************** *************
          // Rule: password is not blank
          //*************** *************** *************** *************
          if (strNewPass1 == ''){
          alert('New password may not be left blank.');
          returnValue = false;
          }


          //*************** *************** *************** *************
          // Rule: password meets minimum length requirements
          //*************** *************** *************** *************
          if (strNewPass1.le ngth < minLength){
          alert('New password may not less than ' + minLength + '
          characters long.');
          returnValue = false;
          }

          //*************** *************** *************** *************
          // Rule: password does not contain the name of a Campbell brand
          //*************** *************** *************** *************
          if (strNewPass1.ma tch(/((arnotts|campb ell|franco|godi va|homepride|pa ce|prego|stockp ot|swanson|v-?8|pepperidge|g oldfish))/)){
          alert('New password may not contain the name of a Campbell
          brand.');
          returnValue = false;
          }


          //*************** *************** *************** *************
          // Rule: password contains at least one letter
          //*************** *************** *************** *************
          if (strNewPass1.ma tch(/^[0-9]+$/)){
          alert('New password must contain both letters and numbers.');
          returnValue = false;
          }

          //*************** *************** *************** *************
          // Rule: password contains at least one digit
          //*************** *************** *************** *************
          if (strNewPass1.ma tch(/^[a-zA-Z]+$/)){
          //alert('New password must contain both letters and numbers.');
          errMessage = errMessage + '\n' + 'New password must contain both
          letters and numbers.';
          returnValue = false;
          }

          //*************** *************** *************** *************
          // Rule: password contains no spaces, tabs, etc
          //*************** *************** *************** *************
          if (strNewPass1.ma tch(/\s/)){
          //alert('New password may not contain spaces.');
          errMessage = errMessage + '\n' + 'New password may not contain
          spaces.';
          returnValue = false;
          }


          if (returnValue == false){ alert(errMessag e); }

          //if this returns false to the onSubmit() function within
          //the <form> tag, then the form submission will be cancelled
          return returnValue;

          }

          Comment

          • bruce

            #6
            Re: regEx in Javascript

            vishantu@hotmai l.com (Vishant) wrote in message news:<2471c68d. 0406070007.2e05 df9a@posting.go ogle.com>...[color=blue]
            > Hi,
            >
            > I'm new to javascript and regEx and trying to solve the following
            > problem.
            >
            > I have a function which validates the password if there is a number:
            > -------------------------------------------------
            > function findNumeric(str _obj){
            > regEx = /\d/;
            > if (str_obj.match( regEx))
            > return true;
            > else
            > return false;
            > }
            > --------------------------------------------------
            > The problem arises when I put a password with a space in between e.g:
            > 'test test1'. The fucntion returns false. I've tried '\s' in the
            > regEx but the user can put the space anywhere..
            >
            > Any idea how to solve this problem as I should be able to put any
            > alplanumeric value into the password, including space.
            >
            > Thanks a lot.
            >
            > Vish[/color]


            rather, use:
            bool=regex.test (str_obj)

            The match method returns an array of matches, so it is unclear as to
            how it responds to a true/false test (at least unclear to me!). The
            "test" method is straightforward true/false here.

            Comment

            • Dr John Stockton

              #7
              Re: regEx in Javascript

              JRS: In article <c2fe7ed0.04060 70846.52860f46@ posting.google. com>, seen
              in news:comp.lang. javascript, Shawn Milo <newsgroups@lin urati.net>
              posted at Mon, 7 Jun 2004 09:46:39 :[color=blue]
              >Here is a function I wrote to validate passwords in Javascript.
              >
              >Rules:
              >1. capital and lower-case letters
              >2. at least one digit
              >3. not the same as their user name
              >4. not the same as the old password
              >5. not blank
              >6. minimum length
              >7. at least one letter
              >8. no white-space
              >9. does not contain certain names[/color]

              Test 5 is superfluous, if any of 1, 2, 7 is passed.
              Test 7 is superfluous, if 1 is passed.

              [color=blue]
              > var strOldPass = eval('document. ' + formName + '.' + oldPass +
              >'.value');[/color]

              One who uses eval for that task has evidently not read the FAQ, and has
              but a poor understanding of the language. The rest of the code is not
              necessarily faulty.

              [color=blue]
              > if (new Date('9/26/2003 15:00:00') > new Date()){[/color]

              The default assumption in this newsgroup is that code is for the World-
              Wide Web, and may be executed by any approximately-current browser.
              That date form is used, in ordinary life, only by Americans and a few
              wannabes; indeed, it conflicts with a FIPS as well as with ISO. Can one
              be sure, therefore, that it will always be interpreted as the 26th day
              of the 9th month of 2003, and not as 2005 Feb 9th - and, if so, on what
              basis?

              The form new Date('2003/09/26 15:00:00') is safer, is more nearly
              compliant with ISO & FIPS, and is most unlikely to be interpreted as
              2005 Feb 9th. // 2003-09-26 fails, at least in MSIE4.

              [color=blue]
              > if (returnValue == false){ alert(errMessag e); }[/color]

              Better as if (!returnValue) ...



              Vishant : <URL:http://www.merlyn.demo n.co.uk/js-valid.htm> may help you.

              --
              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
              <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              Working...