开发者

validating and submitting with 'if' and 'else' using PHP

This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.

The problem is, if the last 'if' is not met, then the 'else' will fire.

This means as long as a valid email address is entered the form will submit, even if other fields are blank.

How can I make so that all requirements must be met for the form to submit

if(empty($_POST['company'])) {
  echo '<script type="text/javascript">
    $(document).ready(function() { 
    $("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
    });
    </script>
  ';
}
if(empty($_POST['name'])) {
  echo '<script type="text/javascript">
    $(document).ready(function() { 
    $("#nameForm").animate({background开发者_开发问答Color:"#ffbfbf"},500);
    });
    </script>
  ';
}
if(empty($_POST['email'])) {
  echo '<script type="text/javascript">
    $(document).ready(function() { 
    $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
    });
    </script>
  ';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
  echo '<script type="text/javascript">
    $(document).ready(function() { 
    $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
    });
    </script>
  ';
}
else { 
  //submits to database... 
}


You can use a flag as:

$isValid = true;

if(empty($_POST['company'])) {
  $isValid = false;
  // your echo
}

Similarly add the $isValid = false; for all the other if bodies.

Finally remove your else part and replace it with:

if($isValid) {
 // submit to DB.
}


you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation. like so:

if() {

} elseif() {

} else {
 ...
}

or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...


<?php
$error = 1;
if(empty($_POST['company'])) {
                echo '<script type="text/javascript">
                    $(document).ready(function() { 
                        $("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
                    });
                    </script>
                     ';
                     $error = 0;
            }
            if(empty($_POST['name'])) {
                echo '<script type="text/javascript">
                    $(document).ready(function() { 
                        $("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
                    });
                    </script>
                     ';
                      $error = 0;
            }
            if(empty($_POST['email'])) {
                echo '<script type="text/javascript">
                    $(document).ready(function() { 
                        $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                    });
                    </script>
                     ';
                      $error = 0;
            }
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
                echo '<script type="text/javascript">
                    $(document).ready(function() { 
                        $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                    });
                    </script>
                     ';
                      $error = 0;
            }
                if($error == 1) { //submits to database...
                }
?>


There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.

// loop through all submitted fields

foreach( $_POST as $key => $value){

   // see if the field is blank

   if($value=="" || $value is null){

      // if blank output highlighting JS

      echo "<script type='text/javascript'>
       $(document).ready(function() { 
       $('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
       });
      </script>";

      // variable to value showing form is invalid in some way

      $invalid=1;
   }

}

 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
            echo '<script type="text/javascript">
                $(document).ready(function() { 
                    $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                });
                </script>
                 ';
     $invalid= 1;
 }

// if form invalid variable not set, submit to DB

if($invalid!=1){
   // submit to DB
}

If you want to be super efficient you can simply use:

// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");


// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
    foreach( $invalid_fields as $key => $value){
          echo "<script type='text/javascript'>
           $(document).ready(function() { 
           $('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
           });
          </script>";
     }
     $error = 1;
}

 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
            echo '<script type="text/javascript">
                $(document).ready(function() { 
                    $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                });
                </script>
                 ';
     $error = 1;
 }


if($error!=1){
 // submit to DB
}


Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false. Then rewrite the else-Part and do a

if ($sendToDb) {
    /* Your Db-Write code */
}


Take a flag variable and check like this

$flag=0;  
      if(empty($_POST['company'])) {
                        echo '<script type="text/javascript">
                            $(document).ready(function() { 
                                $("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
                            });
                            </script>
                             ';
                        $flag=1;
                    }
                    if(empty($_POST['name'])) {
                        echo '<script type="text/javascript">
                            $(document).ready(function() { 
                                $("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
                            });
                            </script>
                             ';
                        $flag=1;
                    }
                    if(empty($_POST['email'])) {
                        echo '<script type="text/javascript">
                            $(document).ready(function() { 
                                $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                            });
                            </script>
                             ';
                        $flag=1;
                    }
                    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
                        echo '<script type="text/javascript">
                            $(document).ready(function() { 
                                $("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
                            });
                            </script>
                             ';
                        $flag=1;
                    }
                    if ($flag == 0)
                  {//submit to database
                  }


You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).

Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:

<?php
if (isset($_POST['submit'])) {
    $errors = array();
    // do server-side validation
    if ($_POST['fieldName'] == '') {
        $errors['fieldName'] = 'fieldName is required';
    }
    if (count($errors) == 0) {
        // save your record to the database or whatever
    }
}

And then the following template:

<style>
    .error { border-color: red; }
</style>
<script>
$(document).ready(function() {
    $('form#yourFormId').submit(function() {
        var errors = null;
        if (errors.length > 0) {
            return false;
        }
    });
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
  <input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
  <input type="submit" name="submit">
</form>

This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜