URGENT: form validation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • creative1
    Contributor
    • Sep 2007
    • 274

    URGENT: form validation

    I am trying form valdiation with javascript but it never call the function. can someone please test this code and see why it is like that. It screwed up my mind.
    here is my code:
    Code:
    <!-- Java Script form form validation and entries -->
    <script language="JavaScript">
    function checkForm()
    {
    alert("I am called");
       var cfirstname, cemail, cpass, clastname;
        
       with(window.document.msgform)
       {
          cfirstname    = firstname;
          cemail   = email;
          cpass = pass;
          clastname = lastname;
       }
    
       if(trim(cfirstname.value) == '')
       {
          alert('Please enter your first name');
          cfirstname.focus();
          return false;
       }
       else if(trim(cemail.value) == '')
       {
          alert('Please enter your email');
          cemail.focus();
          return false;
       }
       else if(!isEmail(trim(cemail.value))) // validate email address
       {
          alert('Email address is not valid');
          cemail.focus();
          return false;
       }
       else if(trim(cpass.value) == '')
       {
          alert('Please enter your password');
          cpass.focus();
          return false;
       }
       else if(trim(clastname.value) == '')
       {
          alert('Please enter your lastname');
          clastname.focus();
          return false;
       }
       else
       {
          cfirstname.value    = trim(cfirstname.value);
          cemail.value   = trim(cemail.value);
          cpass.value = trim(cpass.value);
          clastname.value = trim(clastname.value);
          return true;
       }
    }
    
    function trim(str)
    {
       return str.replace(/^\s+|\s+$/g,'');
    }
    
    function isEmail(str)
    {
       var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|
    ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|
    bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|
    ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|
    dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|
    gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|
    hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|
    kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|
    ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|
    mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|
    nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|
    re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|
    su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|
    ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|
    zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
    
    return regex.test(str);
    }
    </script>
    
    
    <?php 
    // Connects to your Database 
    include_once ('connection.php');
    include_once ('class.countries.inc.php');
    //This code runs if the form has been submitted
    if (isset($_POST['submit'])) { 
    echo("going to check");
    echo "<SCRIPT LANGUAGE='javascript'>checkForm();</SCRIPT>";
    //This makes sure they did not leave any fields blank
    if (!$_POST['firstname'] |!$_POST['lastname'] |!$_POST['email'] | !$_POST['pass'] | !$_POST['pass2'] | !$_POST['company'] | !$_POST['address1']| !$_POST['city']| !$_POST['province']
    	| !$_POST['country']| !$_POST['postalcode']| !$_POST['phone']| !$_POST['sub1']| !$_POST['sub2']
    	) {
    die('You did not complete all of the required fields');
    }
    // checks if the username is in use
    if (!get_magic_quotes_gpc()) {
    	$_POST['email'] = addslashes($_POST['email']);
    }
    	$usercheck = $_POST['email'];
    	$check = mysql_query("SELECT email FROM member WHERE email = '$usercheck'") 
    	or die(mysql_error());
    	$check2 = mysql_num_rows($check);
    //check if the name exists it gives an error
    if ($check2 != 0) {
    	die('Sorry, the email '.$_POST['email'].' is already in use.');
    }
    //  makes sure both passwords entered match
    if ($_POST['pass'] != $_POST['pass2']) {
    	die('Your passwords did not match. ');
    }
    // encrypt the password and add slashes if needed
    	$_POST['pass'] = md5($_POST['pass']);
    // check for addslashes	
    if (!get_magic_quotes_gpc()) {
    	$_POST['firstname'] = addslashes($_POST['firstname']);
    	$_POST['lastname'] = addslashes($_POST['lastname']);
    	$_POST['pass'] = addslashes($_POST['pass']);
    	$_POST['email'] = addslashes($_POST['email']);
    	$_POST['company'] = addslashes($_POST['company']);
    	$_POST['address1'] = addslashes($_POST['address1']);
    	$_POST['city'] = addslashes($_POST['city']);
    	$_POST['province'] = addslashes($_POST['province']);
    	$_POST['country'] = addslashes($_POST['country']);
    	$_POST['postalcode'] = addslashes($_POST['postalcode']);
    	$_POST['phone'] = addslashes($_POST['phone']);
    	$_POST['sub1'] = addslashes($_POST['sub1']);
    	$_POST['sub2'] = addslashes($_POST['sub2']);
    }
    
    //  insert it into the database
    /* 	$insert = "INSERT INTO member (firstname,lastname,company,region,title,address1,address2,city,province,country,postalcode,
    				phone,fax,email,password,website,noofsubscriber,noofaddressablesubscriber)
    		VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['company']."', '".$_POST['region']."',
    				'".$_POST['title']."', '".$_POST['address1']."', '".$_POST['address2']."', '".$_POST['city']."', '".$_POST['province']."',
    				'".$_POST['country']."',' ".$_POST['postalcode']."', '".$_POST['phone']."', '".$_POST['fax']."', '".$_POST['email']."', '".$_POST['pass']."',
    				'".$_POST['website']."', '".$_POST['sub1']."', '".$_POST['sub2']."')";
    		$add_member = mysql_query($insert); */
    		$insert = "INSERT INTO member (firstname,lastname,company,region,title,
    				   address1,address2,city,province,country,postalcode,
    				   phone,ext,fax,email,password,website,noofsubscriber,noofaddressablesubscriber)
    		VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['company']."', '".$_POST['region']."', '".$_POST['title']."',
    				'".$_POST['address1']."', '".$_POST['address2']."', '".$_POST['city']."', '".$_POST['province']."', '".$_POST['country']."', '".$_POST['postalcode']."',
    				'".$_POST['phone']."', '".$_POST['ext']."', '".$_POST['fax']."', '".$_POST['email']."', '".$_POST['pass']."',
    				'".$_POST['website']."', '".$_POST['sub1']."', '".$_POST['sub2']."')";
    		$add_member = mysql_query($insert);
    ?>
    <h1>Registered</h1>
    <p>Thank you, you have registered - you may now login</a>.</p>
    <?php 
    } 
    else 
    { 
    ?>
    <!-- action="<php echo $_SERVER['PHP_SELF']; ?>" -->
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="msgform" >
    <table border="0">
    <tr><td>First Name:</td><td>
    <input type="text" name="firstname" maxlength="50" size=50>
    </td></tr>
    <tr><td>Last Name:</td><td>
    <input type="text" name="lastname" maxlength="50" size=50>
    </td></tr>
    <tr><td>Company:</td><td>
    <input type="text" name="company" maxlength="150" size=60>
    </td></tr>
    <tr><td>Divion/Region:</td><td>
    <input type="text" name="region" maxlength="50" size=50>
    </td></tr>
    <tr><td>Title:</td><td>
    <input type="text" name="title" maxlength="50" size=50>
    </td></tr>
    <tr><td>Address 1:</td><td>
    <input type="text" name="address1" maxlength="150" size=60>
    </td></tr>
    <tr><td>Address 2:</td><td>
    <input type="text" name="address2" maxlength="150" size=60>
    </td></tr>
    <tr><td>City:</td><td>
    <input type="text" name="city" maxlength="50" size=50>
    </td></tr>
    <tr><td>State/Province:</td><td>
    <input type="text" name="province" maxlength="50" size=50>
    </td></tr>
    <tr><td>Country:</td><td>
    <!-- <input type="text" name="country" maxlength="50"> -->
    <?php
    $countryObj = new countries;
          $countryselect = $countryObj->countrySelect(
             array('name'=>'country',
                  'style'=>'width: 200px; color: blue;'
          ),$country?$country:"ca");
     
       echo $countryselect;
      ?>
    </td></tr>
    <tr><td>Zip/Postal Code:</td><td>
    <input type="text" name="postalcode" maxlength="6" size=50>
    </td></tr>
    <tr><td>Phone:</td><td>
    <input type="text" name="phone" maxlength="15"> Ext: <input type="text" name="ext" maxlength="4" size=4>
    </td></tr>
    <tr><td>Fax:</td><td>
    <input type="text" name="fax" maxlength="15" size=50>
    </td></tr>
    <tr><td>Email:</td><td>
    <input type="text" name="email" maxlength="100" size=60>
    </td></tr>
    <tr><td>Password:</td><td>
    <input type="password" name="pass" maxlength="10" size=12>
    </td></tr>
    <tr><td>Confirm Password:</td><td>
    <input type="password" name="pass2" maxlength="10" size=12>
    </td></tr>
    <tr><td>Website:</td><td>
    <input type="text" name="website" maxlength="100" size=60>
    </td></tr>
    <tr><td># of Subscribes:</td><td>
    <input type="text" name="sub1" maxlength="5" size=4>
    </td></tr>
    <tr><td># of Addressable Subscribers:</td><td>
    <input type="text" name="sub2" maxlength="5" size=4>
    </td></tr>
    <tr><th colspan=2><input type="submit" name="submit" value="Submit Registeration" ></th></tr> </table>
    </form>
    
    <?php
    }
    ?>
    Last edited by Atli; Jul 31 '08, 08:19 PM. Reason: Added a few spaces in the huge line so it wouldn't streach the frame
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Are you calling the JavaScript function to check the fields after they have been submitted? That won't work. At that point there will be no fields to check.

    Try attaching the JavaScript check function to the forms onsubmit event, or the submit buttons onclick event.

    Also, the huge regex variable in your JavaScript code contains line-breaks, which is not allowed.

    Comment

    • Markus
      Recognized Expert Expert
      • Jun 2007
      • 6092

      #3
      If the *Javascript* function isn't called, then this *isn't* a PHP problem.

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Originally posted by markusn00b
        If the *Javascript* function isn't called, then this *isn't* a PHP problem.
        Agreed. Moving to the JavaScript forum....

        Now then.

        Try adding an onsubmit handler to your form.

        Comment

        • creative1
          Contributor
          • Sep 2007
          • 274

          #5
          I am lost in this combination. I tried everything thing onsubmit() for form, action for form and onlick for submit button. Nothing worked at all except time waste. I alwasy prefer javascript for form validation but now...I dropped the idea to use javascript for php form validation, and used php-form-validation functions for this purpose. It took me a while to write that but that worked . If some want to post how i did that I'll be happy to do that.
          Thanks All

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5388

            #6
            please show how you tried to call the 'checkForm'-method on submit ... the validation must return a boolean value and the line should be similar to the following:

            [CODE=html]<form name="my_form" onsubmit="retur n checkForm();"/>[/CODE]
            kind regards

            Comment

            • RamananKalirajan
              Contributor
              • Mar 2008
              • 608

              #7
              Hi Dude, this is a simple javascript validation. just try this code this may help you

              [HTML]</html>
              <head>
              <script type="text/javascript">
              function validate()
              {
              var chars = document.getEle mentById('field ').value;
              if (chars.length < 130)
              {
              alert("The news story content must be a minimum of 130 characters to properly display. Please enter more content and re-submit the form.");
              return false;
              }
              else
              {
              return true;
              }
              }
              </script>
              </head>
              <form action="demo.ht ml" method="post" onSubmit="retur n validate()">
              <textarea id="field">
              </textarea>
              <input type="submit" value="Submit Me">
              </form>
              </html>[/HTML]

              Regards
              Ramanan Kalirajan

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Originally posted by creative1
                I am lost in this combination. I tried everything thing onsubmit() for form, action for form and onlick for submit button. Nothing worked at all except time waste. I alwasy prefer javascript for form validation but now...I dropped the idea to use javascript for php form validation, and used php-form-validation functions for this purpose.
                That was a big mistake in the first place. You should never depend on JavaScript validation alone. It's only there as a convenience to avoid unnecessary trips to the server. You MUST have server-side validation at all times.

                Comment

                Working...