Loading ...
Sorry, an error occurred while loading the content.
 

Simple string validation

Expand Messages
  • potain
    Hi I am learning JS and have been asked to write a function that prompts a user to choose a new user ID that is between 6-14 characters long and contains no
    Message 1 of 1 , Feb 23, 2010
      Hi

      I am learning JS and have been asked to write a function that prompts a user to choose a new user ID that is between 6-14 characters long and contains no spaces. The function should test the user's input and alert the user that a) the ID is valid, or b) the ID is too short, too long or contains spaces. The function should loop until the user either enters a valid password or clicks Cancel. It needs to use a do while loop.

      This is what I've come up with below but this is what my teacher tells me and I am totally confused:

      The error generated is because you algorithm has called yourid.length when there is nothing in yourid because you have click cancel.

      Your algorithm here doesn't function correctly because once you find an error you ask for a new id but don't check all 3 properties again (short, long, spaces).

      You should keep track of whether an error has been made and if so go to the next iteration in the do while loop and start again with a prompt. There should only be one prompt per loop iteration ata maximum.

      Instead of using a for loop look up the indexOf function. This would be a better choice than the charAt function.

      The following code isn't valid as it doesn't follow the correct syntax.

      if (yourid.charAt()==" ") {
      alert("No spaces allowed!")

      ------------------------------------------------------------------
      <head>
      <title>StringPractice</title>

      <!--Code the function here-->
      <script type='text/javascript'>
      function getid(){
      var yourid=prompt("Enter your ID:", "");
      if (yourid!=null){
      do{
      for (i=0;i <yourid.length; i++){
      if (yourid.charAt(i) == " "){
      alert("No spaces allowed!")
      yourid=prompt("Enter your ID:", "");}
      }
      if (yourid.length < 6){
      alert("That ID is too short, need 6 or more characters!")
      yourid=prompt("Enter your ID:", "");
      }else if (yourid.length > 14){
      alert("That ID is too long, only 14 chareacters allowed!")
      yourid=prompt("Enter your ID:", "");
      }
      }
      while (yourid >5 && yourid <15);

      alert("Your ID is valid")

      }else alert("Operation Cancelled")
      }

      </script>

      </head>
      <body bgcolor="#88CCEE">
      <h1>String Practice</h1>
      <!--Code button here-->
      <form>
      <INPUT Type="button" Value="Enter your ID!" OnCLick="getid()">
      </form>
      </body>
      </html>


      Any help will be much appreciated. Thank you.
    Your message has been successfully submitted and would be delivered to recipients shortly.