#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2009
    Posts
    95
    Rep Power
    11

    Help with form onsubmit attribute


    Hi,

    I have a form, and am trying to use javascript to validate what the user enters, and THEN I'm trying to perform some PHP validation afterwards.

    If I use:

    Code:
    <form method='post' onsubmit='return checkForm(this)' action=''>
    The javascript validation works fine.

    If I remove the javascript validation, and add the php validation:

    Code:
    <form method='post' action='mailform.php'>
    The php validation works fine.

    But when I try both:

    Code:
    <form method='post' onsubmit='return checkForm(this)' action='mailform.php'>
    Only the javascript validation works. The PHP validation is never called.

    Here is my webpage which is straight from w3schools.

    (I added the javascript validation which is in an external file, link to from within the <head> section).

    mailform.php
    Code:
    <html>
    <head>
    <script src="contactus.js"></script>
    </head>
    <body>
    <?php
    function spamcheck($field)
      {
      //filter_var() sanitizes the e-mail
      //address using FILTER_SANITIZE_EMAIL
      $field=filter_var($field, FILTER_SANITIZE_EMAIL);
    
      //filter_var() validates the e-mail
      //address using FILTER_VALIDATE_EMAIL
      if(filter_var($field, FILTER_VALIDATE_EMAIL))
        {
        return TRUE;
        }
      else
        {
        return FALSE;
        }
      }
    
    if (isset($_REQUEST['email']))
      {//if "email" is filled out, proceed
    
      //check if the email address is invalid
      $mailcheck = spamcheck($_REQUEST['email']);
      if ($mailcheck==FALSE)
        {
        echo "Invalid input";
        }
      else
        {//send email
        $email = $_REQUEST['email'] ;
        $subject = $_REQUEST['subject'] ;
        $message = $_REQUEST['message'] ;
        mail("someone@example.com", "Subject: $subject",
        $message, "From: $email" );
        echo "Thank you for using our mail form";
        }
      }
    else
      {//if "email" is not filled out, display the form
      echo "<form method='post' action='mailform.php'>
      Email: <input name='email' type='text' /><br />
      Subject: <input name='subject' type='text' /><br />
      Message:<br />
      <textarea name='message' rows='15' cols='40'>
      </textarea><br />
      <input type='submit' />
      </form>";
      }
    ?>
    
    </body>
    </html>
    How can I get both sets of validation to work?

    I want to first use the javascript validation, then run the PHP validation.

    Really appreciate any help!

    Triffic

    Javascript file:

    contactus.js
    Code:
    //------------------------------------
    //The form's onsubmit attribute calls this function first. 'contactUs' is the THIS parameter from the form.
    //------------------------------------
    function checkForm(contactUs) {
    var check = "";//create an empty string
    
    	//use the checkEmail() function to validate the email field. contactUs.email == this.email.
    	//put what checkEmail() returns into the string 'check'
      check += checkEmail(contactUs.email);
    
          
      if (check != "") {//if the string 'check' 
        alert("There are some mistakes in the form:\n" + check);//javascript validation not passed
        return false;
      }
    
      alert("Thank you.");//javascript validation has passed
      return false;
    }
    function checkNotEmpty(box) {
        var invalid = "";
     
        if (box.value.length == 0) {
            box.style.background = '#00FF33'; 
            invalid = "Please fill in the required fields.\n"
        } else {
            box.style.background = 'White';
        }
        return invalid;  
    }
    
    function trim(s)
    {
      return s.replace(/^\s+|\s+$/, '');
    }
    
    //////////////////////////////////////////////////////
    
    function checkEmail(box) {
    //'box' is THIS. 
    //create an empty string
        var invalid="";
    	//strip white/blank space from the email address entered
        var tfld = trim(box.value);
        //create the email filter
    	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
        //create the illegal characters filter
    	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
       
        if (box.value == "") {//test email is not empty
            box.style.background = '#00FF33';
            invalid = "You didn't enter an email address.\n";
        } else if (!emailFilter.test(tfld)) {  //test email for valid address
            box.style.background = '#00FF33';
            invalid = "Please enter a valid email address.\n";
        } else if (box.value.match(illegalChars)) {//test email for illegal characters
            box.style.background = '#00FF33';
            invalid = "The email address contains illegal characters.\n";
        } else {//
            box.style.background = 'White';
        }
        return invalid;
    }
    Last edited by Triffic; January 27th, 2010 at 09:06 PM.
  2. #2
  3. No Profile Picture
    I AM A GOLDEN GOD
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Apr 2003
    Location
    Camarillo, California
    Posts
    5,929
    Rep Power
    1171
    EDIT: misread your original code, my bad.

    Your PHP script has some problems. Namely, you should never use $_REQUEST, but either $_POST or $_GET. What if I were to call up the URL http://www.yourdomain.com/contactform.html?email=badstuff? It will accept whatever i pass it as the $_REQUEST['email'] value, bypassing your POST form altogether.

    Additionally, this code doesn't do precisely what you think it does:
    PHP Code:
    if (isset($_REQUEST['email']))
      {
    //if "email" is filled out, proceed 
    Technically, all that does is check for a variable in the $_REQUEST superglobal that is set, it doesn't check for the presence of an actual string. You should instead use [phpnet=empty]empty()[/phpnet]. In the case of a $_POST index, it actually would work properly.

    Also, we'll want to look at your filter_var() function so we can see what it's trying to do to validate the data.

    Suggest moving this to JavaScript or PHP, whichever direction the thread takes.

    Comments on this post

    • Triffic agrees : Really appreciate that! Thanks very much :)
    Last edited by lnxgeek; January 27th, 2010 at 09:31 PM. Reason: Misread the original code, sorry.
    "Seriously, we're not a search engine, we're actual people." ~ ManiacDan

    BookMooch.com : Give books away. Get books you want.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2009
    Posts
    95
    Rep Power
    11
    wow, thanks for all the help lnxgeek !

    A lot of information.

    I certainly want to address the issue of the $_REQUEST first.

    Thanks for pointing that out!!

    Reading your comment:

    In the case of a $_POST index, it actually would work properly.
    I have changed all the instances of $_REQUEST into $_POST.

    The form still seems to work correctly, do I not now need to use empty()?

    Thanks so much !!

IMN logo majestic logo threadwatch logo seochat tools logo