Checking for spaces in input validation.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    Checking for spaces in input validation.

    Making a basic validation script, i hit a snag.

    If user was to input say " "(minus quotes), into the textfield and then submit it the length check i have used would return it as true and therefore execute the rest of the code.

    Is there a way to compensate for spaces, as to include them in the length?

    Or do you have a different idea?

    The code:
    [code=javascript]
    function validateInput()
    {
    var username = document.sign_u p.username
    var password = document.sign_u p.password
    var email = document.sign_u p.email
    var secondary_email = document.sign_u p.secondary_ema il
    if(username.len gth <= 6 || username.value == ""){ //check for length
    alert("Username must be longer than 6 characters!\n\n- mahcuz")
    }
    else if(username.len gth >= 14){ //check for length
    alert("Username must be shorter than 14 characters!\n\n- mahcuz")
    }
    else{
    document.sign_u p.submit()
    }
    }
    [/code]
  • iam_clint
    Recognized Expert Top Contributor
    • Jul 2006
    • 1207

    #2
    Your question is hard to answer because I don't understand what you want to do... do you want the spaces to be stripped and the spaces removed from the length of the input? so the code halts?

    Comment

    • jasone
      New Member
      • Mar 2007
      • 66

      #3
      Hi,
      just to confirm your question,
      do you want a validation like the one on this website which i am currently working on: http://www.simplicity-design.co.uk/

      if you go to the register section and try to enter a name under 5 characters an error is shown.

      if this is the problem will happily provide the script for you..

      jason

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        hi ...

        you may use the following adaption for the length check:

        [CODE=javascript]username.replac e(/ /g, '').length;[/CODE]
        kind regards

        Comment

        • Markus
          Recognized Expert Expert
          • Jun 2007
          • 6092

          #5
          How to include spaces in length check?

          This little thing is bugging me ¬_¬

          I'm trying to validate a form and then submit it through javascript.

          But i've hit the folllowing problem:

          when i do
          [code=javascript]
          function validateInput()
          {
          var username = document.form.u sername
          if(username.len gth <= 6){
          alert("Username must be longer than 6 characters!")
          }
          }
          [/code]
          But if i enter a space(and nothing else), it for some reason validates and then submits the form.

          Anyone know how i can counter this?

          Comment

          • Logician
            New Member
            • Feb 2007
            • 210

            #6
            Originally posted by markusn00b

            [code=javascript]
            var username = document.form.u sername
            if(username.len gth <= 6){
            [/code]
            You need to read the .value property, and you should always strip any leading or trailing spaces before reading the string, and display that it has been done:

            [CODE=javascript]
            var username = document.form.u sername.value.r eplace(/^\s+|\s+$/g,'');
            document.form.u sername.value=u sername;
            if( username.length <= 6 )
            alert("Username must be longer than 6 characters!")
            [/CODE]

            Comment

            • Markus
              Recognized Expert Expert
              • Jun 2007
              • 6092

              #7
              Originally posted by Logician
              You need to read the .value property, and you should always strip any leading or trailing spaces before reading the string, and display that it has been done:

              [CODE=javascript]
              var username = document.form.u sername.value.r eplace(/^\s+|\s+$/g,'');
              document.form.u sername.value=u sername;
              if( username.length <= 6 )
              alert("Username must be longer than 6 characters!")
              [/CODE]
              Thanks for that!

              A question though:
              [code=javascript]
              (/^\s+|\s+$/g,'');
              [/code]
              Could you explain that?

              Thanks :)

              Comment

              • gits
                Recognized Expert Moderator Expert
                • May 2007
                • 5388

                #8
                hi ...

                that is a regular Expression that matches leading and/or trailing spaces of the value you want to check. using it with the replace method the way it was done cuts off the spaces and so trims your value for such spaces ...

                kind regards

                Comment

                • Markus
                  Recognized Expert Expert
                  • Jun 2007
                  • 6092

                  #9
                  Originally posted by gits
                  hi ...

                  that is a regular Expression that matches leading and/or trailing spaces of the value you want to check. using it with the replace method the way it was done cuts off the spaces and so trims your value for such spaces ...

                  kind regards
                  Thanks :)

                  but i just changed it to
                  [code=javascript]
                  (/ /, '')
                  [/code]
                  It seems to work, but is there something it's not doing now by me changing it?

                  Comment

                  • Logician
                    New Member
                    • Feb 2007
                    • 210

                    #10
                    Originally posted by markusn00b
                    Thanks :)

                    but i just changed it to
                    [code=javascript]
                    (/ /, '')
                    [/code]
                    It seems to work, but is there something it's not doing now by me changing it?
                    Yes - it's only removing the first space that it finds, which is why it wasn't given like that.

                    Comment

                    • jasone
                      New Member
                      • Mar 2007
                      • 66

                      #11
                      hey gits...

                      as promissed this little script should help with your username validation, you may need to talor it a little to your script but the basics should be clear!

                      Code:
                       (javascript)
                       /* Username error checking */
                            $field = "user";  //Use field name for username
                            if(!$subuser || strlen($subuser = trim($subuser)) == 0){
                               $form->setError($field, "* Username not entered");
                            }
                            else{
                               /* Spruce up username, check length */
                               $subuser = stripslashes($subuser);
                               if(strlen($subuser) < 5){
                                  $form->setError($field, "* Username below 5 characters");
                               }
                               else if(strlen($subuser) > 30){
                                  $form->setError($field, "* Username above 30 characters");
                               }
                               /* Check if username is not alphanumeric */
                               else if(!eregi("^([0-9a-z])+$", $subuser)){
                                  $form->setError($field, "* Username not alphanumeric");
                               }
                               /* Check if username is reserved */
                               else if(strcasecmp($subuser, GUEST_NAME) == 0){
                                  $form->setError($field, "* Username reserved word");
                               }
                               /* Check if username is already in use */
                               else if($database->usernameTaken($subuser)){
                                  $form->setError($field, "* Username already in use");
                               }
                               /* Check if username is banned */
                               else if($database->usernameBanned($subuser)){
                                  $form->setError($field, "* Username banned");
                               }
                            }
                      
                            /* Password error checking */
                            $field = "pass";  //Use field name for password
                            if(!$subpass){
                               $form->setError($field, "* Password not entered");
                            }
                            else{
                               /* Spruce up password and check length*/
                               $subpass = stripslashes($subpass);
                               if(strlen($subpass) < 4){
                                  $form->setError($field, "* Password too short");
                               }
                               /* Check if password is not alphanumeric */
                               else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
                                  $form->setError($field, "* Password not alphanumeric");
                               }
                               /**
                                * Note: I trimmed the password only after I checked the length
                                * because if you fill the password field up with spaces
                                * it looks like a lot more characters than 4, so it looks
                                * kind of stupid to report "password too short".
                                */
                            }

                      Comment

                      • Markus
                        Recognized Expert Expert
                        • Jun 2007
                        • 6092

                        #12
                        Thanks for that jasone.

                        Here is my finished code :)
                        All written by moi, with the help of (how do you say 'you' in french?)
                        [code=javascript]
                        /********
                        Code written by Mark Skilbeck
                        http://mahcuz.com
                        5,7"
                        black hair
                        skinny jeans!
                        ********/
                        function validateEmail(e mail)
                        {
                        email = email;
                        AtPos = email.indexOf(" @");
                        StopPos = email.lastIndex Of(".");
                        /*This checks that the '.' and '@' are actually present! The posistion returned by the above variables is an interger and will start at 0 respective of where they are inside the string. If they are not present, there will be no interger returned. Therefore, -1 will declare there is no '.' OR '@' */
                        if(AtPos == -1 || StopPos == -1){
                        return false;
                        }
                        /*Here we check for the (last) posistion of '.' against the posistion of '@' i.e. if the (last) posistion of '.' comes BEFORE the '@', the email is invalid! */
                        if (StopPos < AtPos) {
                        return false;
                        }
                        /*We now need to check what comes between the '@' and '.' If the space between the two is equal to 1, the email is returned as false. */
                        if (StopPos - AtPos == 1) {
                        return false;
                        }
                        /*Nearly done. '@fooledyou.com ' would still be slipping through! We simply check to see if the placement of '@' is 0 (remember 0 is where numbering starts! NOT 1)*/
                        if (AtPos == 0){
                        return false;
                        }
                        /*And finally 'youvebeen@fool ed.' will be the last situation (for now) that we must wittle out.
                        We compare the posistion of '.' to the length of the email(minus one) to make sure '.' is not at the end! */
                        if (StopPos == email.length - 1){
                        return false;
                        }
                        // DONE!
                        }

                        function username_chars( username)
                        {
                        var username = username;
                        username.replac e(/[^a-zA-Z0-9]/g,'');
                        return username;
                        }
                        function validateInput()
                        {
                        var email = document.sign_u p.email.value.r eplace(/ /,'') //email with spaces stripped
                        document.sign_u p.email.value = email;

                        var username = document.sign_u p.username.valu e.replace(/[^a-zA-Z0-9_-]/g,'') //username with spaces stripped
                        document.sign_u p.username.valu e = username;

                        var secondary_email = document.sign_u p.secondary_ema il.value.replac e(/ /g,''); //sec_email with spaces stripped
                        document.sign_u p.secondary_ema il.value = secondary_email ;

                        if(username.len gth <= 6 || username.length >= 14)
                        {
                        alert("Username must be 7-14 characters long!\n\n username: '"+username+ "', is invalid\n\n- mahcuz");
                        username.focus( )
                        }
                        else if(validateEmai l(email) === false){

                        /*call the validate email function. If the return is FALSE, alert. */
                        alert("Please enter a valid email!\n\nemail adress: '"+email+"', not valid\n\n- mahcuz");
                        email.focus();
                        }
                        else if(email == secondary_email ){
                        alert("The secondary email isn't necessary, but if you're going to use it, don't be a tard and put in the email you've selected as your primary one!!");
                        document.sign_u p.secondary_ema il.value = "New email!";
                        }
                        else{
                        document.sign_u p.submit()
                        }
                        }
                        function toEmpty()
                        {
                        var text1 = document.sign_u p.secondary_ema il
                        if(text1.value == "New email!"){
                        text1.value = "";
                        }
                        }
                        [/code]

                        Comment

                        • Markus
                          Recognized Expert Expert
                          • Jun 2007
                          • 6092

                          #13
                          Originally posted by Logician
                          Yes - it's only removing the first space that it finds, which is why it wasn't given like that.
                          Sorry i meant to add a 'g' to the end.

                          Comment

                          • Logician
                            New Member
                            • Feb 2007
                            • 210

                            #14
                            Originally posted by markusn00b
                            Sorry i meant to add a 'g' to the end.
                            That would remove intermediate spaces also.

                            Comment

                            • acoder
                              Recognized Expert MVP
                              • Nov 2006
                              • 16032

                              #15
                              Merged threads on the same topic.

                              Comment

                              Working...