SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: Form validation

  1. #1
    SitePoint Guru
    Join Date
    Nov 2000
    Posts
    740
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Form validation

    What is wrong with my Form validation code?

    Code:
    <script type="text/javascript">
    function validateform(fields)
    {
    if (email=="" | email==null | email==false) 
    {
    alert("Enter email");
    return false;
    }
    }
    </script>
    
    <form id="form1" name="form1" method="post" action="step2.php" onsubmit="validateform">
    Thanks,

    Jon

  2. #2
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    for "OR" statements, you need to use a double pipe ||, not just a single pipe.

    Also, when you want the form to be submitted, you should return true.

    For the variable "email", if it's an input element, you need to get its value.

    Code JavaScript:
    var email = document.getElementById('email').value;



    If you're trying to check for a blank address, a better way to do it is to trim whitespace characters and then count the number of characters in the string


    Code JavaScript:
    //this allows you to use the trim() function
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
     
     
    if(email.trim().length>0){ //there are characters }
    else { //there are no characters }
    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain

  3. #3
    SitePoint Guru
    Join Date
    Nov 2000
    Posts
    740
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you! May I ask why doing the trim and character length is the better way?

  4. #4
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    trim is to remove any extra spaces. For instance, if someone hit the space bar a few times in the textbox, without trimming, those spaces would be counted as actual characters.

    As for using length as the condition in the if-statement... it gets around having to declare those three conditions in your if-statement, and replace it with a single condition. It simplifies things.
    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •