0

How to I add validation to this php form so that it verifies that a valid email was input and if not post an error message below the input area. I also need it to make sure that all the fields are filled out and that there is no malicious code entered.

Can anyone please help? Thank you in advance.

<?php
        $name = $_POST['fullname'];
        $email = $_POST['email'];
        $message = $_POST['message'];
  $subjectCustomer = $_POST['subject'];
        $from = 'Contact Form'; 
        $to = 'test@gmail.com'; 
        $subject = "Message from Contact Form: $subjectCustomer";
  $location = "http://www.domain.com";
        
        $body = "From: $name\n E-Mail: $email\n Message: $message\n";
         
   
   ## SEND MESSGAE ##
   
   if ($_POST['submit']) {
   if ($message != '' && $email != '' && $subject != '') {                
         if (mail ($to, $subject, $body, $from)) { 
          echo '<script type="text/javascript">alert("Your message has been sent!"); location.href="index.html";</script>';
      } else { 
         echo '<script type="text/javascript">alert("Something went wrong, go back and try again!"); location.href="index.html/#76industries_contact";</script>'; 
      } 
   } else {
      echo '<script type="text/javascript">alert("You need to fill in all required fields!!"); location.href="index.html/#76industries_contact";</script>';
  }
 }
?>
<form role="form" method="post" action="contact_form.php" >
          <div class="col-md-3">
          
              <div class="form-group">
                <input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30">
              </div> <!-- end form-group -->
              
              <div class="form-group">
                <input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
              </div>  <!-- end form-group -->
              
              <div class="form-group">
                <input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
              </div> <!-- end form-group -->
              
              <div>
               <input id="submit" name="submit" type="submit" value="Send Message" class="btn btn-primary">
              </div> <!-- end button -->
          </div>  <!-- end col-md-3 -->
          
          <div class="form-group">
           <div class="col-md-9">
            <div class="txtarea">
              <textarea name="message" rows="10" class="form-control" id="message" placeholder="Your Message"></textarea>
            </div>  <!-- end txtarea -->
          </div> <!-- end col-md-9 -->
          <div> <!-- end form-group -->
          
          <div class="form-group">
           <div class="col-sm-10 col-sm-offset-2">
            <! Will be used to display an alert to the user>
            </div><!-- end col-sm-10 -->
          </div> <!-- end form-group -->
          </div>
          </div>
        </form>
kami nelson
  • 15
  • 1
  • 6
  • You can use `filter_var()` for the email and all kinds of things like `strip_tags()`, `preg_replace()`, `htmlspecialchars()`, etc. to strip out and/or convert input. – Rasclatt Oct 13 '15 at 05:58
  • how would I implement those exact? – kami nelson Oct 13 '15 at 06:02
  • You can read the manual on each. – Rasclatt Oct 13 '15 at 06:05
  • 1
    If you write much front end code, you're going to be doing stuff like this a fair bit. Do yourself a favor and learn to use a library like [jqueryvalidation](http://jqueryvalidation.org/) – Wesley Smith Oct 13 '15 at 06:07
  • jQuery validation is only good so long as the user doesn't turn off their javascript to circumvent this validation. Server side validation is a requirement. – Rasclatt Oct 13 '15 at 06:25
  • Please follow the given link for the email validation http://stackoverflow.com/questions/19605773/html5-email-validation – Prajeesh Oct 13 '15 at 07:01
  • Check the link and follow the validation tips http://stackoverflow.com/questions/19605773/html5-email-validation – Prajeesh Oct 13 '15 at 07:03

3 Answers3

1

here is jquery validation for email and name

$('#submit').click(function(){
                        var uname=$('#fullname').val();
                        if($('#fullname').val().match('[a-zA-Z]+\\.?')){
                             $("#nameerr").css("visibility","hidden");

                                }
                        else{

                                    $("#nameerr").text("FullName is InValid" ) ;
                                     $("#nameerr").css("visibility","visible");
                                    return false;

                                }

                        });





                        $('#submit').click(function(){
                        var email=$('#email').val();
                        if($('#email').val().match('[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}')){
                            $("#emailerr").css("visibility","hidden");
                        }
                        else
                    {
                            $("#emailerr").text("Email Address is InValid.");
                              $("#emailerr").css("visibility","visible");

                            return false;

                    }

                        });

now you can add another div empty div

<div id="nameerr"> </div>

<div id="emailerr"></div>

now give them css :

 #nameerr,#emailerr{    
         color: red;
         background-color:#FFB2B2;
         visibility : hidden;
         font-weight:bold;
         font-size: 12px;
         box-shadow: 0 0 5px rgba(255, 0, 0, 1);
          width: 150%;
         height:10%;   
    }
Chirag Senjaliya
  • 460
  • 3
  • 16
0

As mentioned above in the comments, you can use many ways to achieve what you want.

You could use PHP or JQuery.

If you would like to use PHP, you most likely will end up doing something like:

$name = htmlspecialchars($_POST['fullname']);
$email = $_POST['email'];
$message = htmlspecialchars($_POST['message']);
$subjectCustomer = htmlspecialchars($_POST['subject']);

This takes all the special html characters in a string and converts them to regular html characters.

You can read more on htmlspecialchars here.

Note: You don't want to do a htmlspecialchars() on email addresses. This will convert the @ and make it useless.


To check if all fields are filled in, you can use the required attribute from HTML.

Example:

<input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30" required>

Notice that I've placed the attribute inside the input tags.

Chris
  • 1,574
  • 4
  • 16
  • 49
0

If you are only looking to achieve client side validation, then I would strongly recommend the jQuery Validation Plugin, that can be found here: http://jqueryvalidation.org/

You can validate your form, on submit with one line of code $("#yourFormName").validate();

Even though you are validating your form's input on the client side, it is still good practice to first check that your variable has some information, then to sanitize your data server side, using a method such as:

if(isset($_POST['fullname'])) { $name = addslashes($_POST['fullname'] }