need code help for basic email and password validation.

Discussion in 'JavaScript' started by confusedone, Apr 17, 2011.

  1. #1
    Working on college assignment, cant figure it out and need help! Basically a form that asks the user to fill in a valid email and password (ill give them the password), doesnt matter if it isnt secure, or if the email accepts dodgy emails (im just verifying the @ and a . and that is ok for the purpose of this. Anyway been trying with this code for ages now and cant see what is wrong but it isnt working, ive swapped it around and at times it does check that it is a valid email, sometimes it allows empty inputs. here is the code

    <script type="text/javascript">
    function validateForm()
    {
    var x=document.forms["myForm"]["email"].value
    var y=document.forms["myForm"]["password"].value

    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
    {
    alert("Not a valid e-mail address");
    return false;
    }

    </script>


    I think i need something like && (y!="123") around the 'if' statement, but not a clue how or where it goes. Basically im going to set the password to 123 so dont have to allow for caps etc. Easiest way to do this, anyone plleeeeeaaasseee??

    Kind regards

    Alan
     
    confusedone, Apr 17, 2011 IP
  2. zerophean

    zerophean Peon

    Messages:
    91
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    zerophean, Apr 18, 2011 IP
  3. AdM.as

    AdM.as Peon

    Messages:
    20
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It looks like the code from hxxp:// www.w3schools.com/jS/js_form_validation.asp, I tried it out on their test page and for the email input it's working correctly. If when you said it allows empty inputs you meant the password input and not the email input, then it's working as it should as you have no checks for the password in the code (but you do refer to this at the end of your post :) )

    If you want to perform a check on the password and verify that it's '123', this is the code to do so:

    function validateForm() {
         var x=document.forms["myForm"]["email"].value
         var y=document.forms["myForm"]["password"].value
         var atpos=x.indexOf("@");
         var dotpos=x.lastIndexOf(".");
    
         if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
              alert("Not a valid e-mail address");
              return false;
         }
    
         if(y != "123") {
              alert("Invalid password");
              return false;
         }
    
         return true;
    }
    Code (markup):
     
    AdM.as, Apr 18, 2011 IP