JM4 JM4 - 5 months ago 12
PHP Question

Validate Form with PHP AND JavaScript?

Is it possible to validate a form with PHP and JavaScript? I'm currently able to do both using my existing

form
, but only on an individual basis.

My overall goal is this:


  1. Validate form using JavaScript client side and present any errors to the user immediately.

  2. If JavaScript validation passes, a flag is created and then the PHP script can begin.



When doing my JavaScript validation, I use the following code within the
form
tag:

<form id="Enroll_Form" action="review.php" method="post" name="Enroll_Form" onsubmit="return Enroll_Form_Validator(this)" language="javascript">


If I want to process the PHP validation I'm forced to rename the action to the
PHP_SELF
file (or simply the same file name I'm using) and remove the 'onsubmit' function.

Answer

UPDATED in responce to comments

First of all, javascript can't be a secure validator, for obvious reasons! it can be a fancy way of displaying alerts and notice but is just sugar!

Real validation must be done in PHP or other server-side language as well as on Database side by checking and formatting values!

This simple script is just a demostration of how you can built a smart validator, but of course is just a proof of concept!


DEMO: http://jsbin.com/aceze/29

$(function() {
    $('#myform').submit(function() {
        var error = false; // flag

        $('.email,.digits,.empty,.some').each(function() {

            var check = this.className;

            if (check == 'empty') if (!checkEmpty(this.value)) error = true;

            if (check == 'digits') if (!checkDigits(this.value)) error = true;

            if (check == 'email') if (!checkEmail(this.value)) error = true;

            if (check == 'some') if (!checkSome(this.value)) error = true;

            if (error) {
                $(this).css('border', '1px solid red');
            } else {
                $(this).css('border', '1px solid green');
            }
        });

        if (error) {
            return false;
        }
    });
});

Then regarding the <form> action, you don't need to have the path of the php page in it, but you must use AJAX for make the POST OR just leave the review.php where is see theese snippets below:

  // FIRST SNIPPET action="#"
           if ( error == false ) {
           //if all is ok give our form it's php
           $(this).attr('action','review.php');
           } else {
           // error  
           // place false here so the form don't submit if validation fail!
           return false;
         }

  // SECOND SNIPPET action="review.php"

          if ( error == true ) {
        // form submit only if validation pass
           return false;
           } 

  // THIRD SNIPPET action="#" AJAX

    if ( error == false ) {
           // success
           } else {
           // error  

         }
     // this false prevent the form submit in anycase, cause we use AJAX
     return false;