Jump to content

Form Validation Help


kevinkhan

Recommended Posts

Im trying to make a script that will only allow use full information in a form on my website... Here is the code i have so far...

 

<?php
  if(isset($_POST['submit']))
      {
          $name = $_GET['name'];
          $email = $_POST['email'];
          $mobile = $_POST['mobile'];
          $comments = $_POST['comments'];

          if(empty($errors))
          {
            $to = "[email protected]";
            $subject = "Event Promotion Enquiry!";
            $body = 
             "First Name: " . $_POST['name'] .
             "\nEmail: " . $_POST['email'] .  
        	   "\nMobile: " . $_POST['mobile'] . 
        	 "\nMessage: " . $_POST['comments'];
           if (mail($to, $subject, $body)) {
            echo("<p>Thanks for submitting your enquiry.</p>");
            }
            else
            {
            echo("<p>Message delivery failed.</p>");
            }
          }
          else
          {
          echo "<p>".$error."</p>";
          }    
      }                   
?>
<form id="form" method="post" action="testing.php"> 
              <p> 
                <label>Name</label><br /> 
                <input type="text" name="name" id="firstName" />      
            </p> 
              <p> 
                <label>Email:</label><br /> 
                <input type="text" name="email" id="email" /> 
                
            </p>               
            <p> 
                <label>Mobile:</label><br /> 
                <input type="text" name="mobile" id="mobile" /> 
                
            </p>                                  
            <p> 
                <label>Comments:</label> <br />
                <textarea name="comments" cols="30" rows="3"></textarea>    
            </p> 
            <p>    <input type="submit" name="submit" value="Submit"  /></p> 
  </form>  

 

I only want the form to be processed if the form fields are correctly filled out..

 

for name i want something like the input to be two words of a minimum of 3 charaters each maybe.. and if the user has not put this i want the script to display an error above the form saying something like "Please insert your full name with a space between your first and last name"

 

for the email field i would like a correctly formatted email address to be used and again if there is an error i would like the message to say something like "Please enter your correct email address"

 

For the phone field i would like the user to only enter a ten digit number

 

and for the comments maybe have a minimum of 20 chars..

 

Can somebody help me with this its bugging me all morning and i cant figure out the logic in it..

 

Thanks for your help...

 

Link to comment
https://forums.phpfreaks.com/topic/192371-form-validation-help/
Share on other sites

for name i want something like the input to be two words of a minimum of 3 charaters each maybe.. and if the user has not put this i want the script to display an error above the form saying something like "Please insert your full name with a space between your first and last name"

 

For validation of the space, and alphabetic values for the letters in the name, you can mess around with a little regex by using --

 

preg_match("^[a-zA-Z ]+$",$name) 

 

which returns the number of matches it finds.

 

Perhaps this is easier though --

 

$name_split = explode(" ",$name);

if(sizeof($name_split) == 2)
{
      $firstname = $name_split[0];
      $lastname = $name_split[1];

      if(strlen($firstname) < 3) echo "The first name is less that 3 characters. Fix this.";
      if(strlen($lastname) < 3) echo "The last name is less that 3 characters. Fix this.";
}

else echo "That name doesn't have a space in between the first and last names, or it has an extra space somewhere else";

 

for the email field i would like a correctly formatted email address to be used and again if there is an error i would like the message to say something like "Please enter your correct email address"

 

Here's the function I personally use -- very extensive.

 

function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

 

For the phone field i would like the user to only enter a ten digit number

 

This depends on if you're accepting dashes between the digits in the #, but if you aren't, you could try --

 

if(strlen($mobile) != 10) echo "The mobile number is not formatted properly.";

 

and for the comments maybe have a minimum of 20 chars..

 

if(strlen($comments) < 20) echo "The comments are too short.";

Thanks for your help guys. I came up with this code in the end

 

<?php



  if(isset($_POST['submit']))
      {
          $firstName = $_POST['firstName'];
          $lastName = $_POST['lastName'];
          $email = $_POST['email'];
          $mobile = $_POST['mobile'];
          $comments = $_POST['comments'];
         
          $errors = array();
          
        function display_errors($error_array)
          {
          echo "<p class=\"errors\">";
          
          foreach($error_array as $error)
            {
            echo $error . "<br />";
            }
            echo "</p>";
          }  
          
         function validateNames($names) 
        {
        return(strlen($names) < 3);
        } 
        
        function validateEmail($strValue) 
        {
           $strPattern = '/([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})/sim';
           return(preg_match($strPattern,$strValue));
        } 
        
        function validateMobile($strValue) 
        {
           $strPattern = '/^\d{10}$/';
           return(preg_match($strPattern,$strValue));
        } 
        
        function validateComments($comments) 
        {
        return(strlen($comments) < 10);
        } 
        
        if(validateNames($firstName)) 
        {    
        $errors[] = 'Please Enter Your First Name';    
        }
        
         if(validateNames($lastName)) 
        {    
        $errors[] = 'Please Enter Your Second Name';    
        }
        
          
        if(!validateEmail($email)) 
        {    
        $errors[] = 'Please Enter Your Correct Email';    
        }
        
        if(!validateMobile($mobile)) 
        {    
        $errors[] = 'Please Enter Your Correct Mobile Number';    
        }
        
        if(validateComments($comments)) 
        {    
        $errors[] = 'Please Enter A Comment More Than 10 Characters';    
        }


          if(empty($errors))
          {
            $to = "[email protected]";
            $subject = "Event Promotion Enquiry!";
            $body = 
             "First Name: " . $_POST['firstName'] .
             "\nLast Name: " . $_POST['lastName'] .
             "\nEmail: " . $_POST['email'] .  
        	   "\nMobile: " . $_POST['mobile'] . 
        	 "\nMessage: " . $_POST['comments'];
        	  $headers = "From: ". $firstName ." ". $lastName . " <" . $email . ">\r\n";


          if (mail($to, $subject, $body, $headers)) {
            echo("<p>Thanks for submitting your enquiry.</p>");
            }
            else
            {
            echo("<p>Message delivery failed.</p>");
            }
          }
          else
          {
          //echo "error";
         display_errors($errors);
          }    
      }                   
?>
<form id="form" method="post" action="testing.php"> 
              <p> 
                <label>First Name</label><br /> 
                <input type="text" name="firstName" value="<?php if(isset($firstName)){echo $firstName;} ?>" />      
            </p> 
            <p> 
                <label>Last Name</label><br /> 
                <input type="text" name="lastName" value="<?php if(isset($lastName)){echo $lastName;} ?>" />      
            </p> 
              <p> 
                <label>Email:</label><br /> 
                <input type="text" name="email" value="<?php if(isset($email)){echo $email;} ?>" /> 
                
            </p>               
            <p> 
                <label>Mobile:</label><br /> 
                <input type="text" name="mobile" value="<?php if(isset($mobile)){echo $mobile;} ?>" /> 
                
            </p>                                  
            <p> 
                <label>Comments:</label> <br />
                <textarea name="comments" cols="30" rows="3" ><?php if(isset($comments)){echo $comments;} ?></textarea>    
            </p> 
            <p>    <input type="submit" name="submit" value="Submit"  /></p> 
  </form>  

 

if there are more than one error how do i limit to displaying only one error at a time...

 

do i need a different loop or how would i go about doing it does anyone know?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.