使用“if”验证并提交以及“其他”使用PHP

发布于 2024-10-06 00:11:13 字数 1089 浏览 3 评论 0原文

这段代码应该检查是否有任何字段为空或无效,如果是,它将把它们变成红色。如果一切正常那么它将发送到数据库。

问题是,如果最后一个“if”不满足,那么“else”将会触发。
这意味着只要输入有效的电子邮件地址,即使其他字段为空,表单也会提交。

我怎样才能满足提交表格的所有要求

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({backgroundColor:"#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... 
}

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({backgroundColor:"#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... 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

你与昨日 2024-10-13 00:11:13

您可以将标志用作:

$isValid = true;

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

类似地,为所有其他 if 主体添加 $isValid = false;

最后删除您的 else 部分并将其替换为:

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

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.
}
相思故 2024-10-13 00:11:13

您可以使用 else if,但是您不会在所有错误字段中看到“红色”,而只会在第一个验证失败的字段中看到“红色”。
像这样:

if() {

} elseif() {

} else {
 ...
}

或者你可以在开始时将某些内容设置为 $error=false ,然后在 if 控制代码中将 error 设置为 true ,然后提交到数据库检查 error 是否仍然为 false ...

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...

脸赞 2024-10-13 00:11:13
<?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...
                }
?>
<?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...
                }
?>
橘虞初梦 2024-10-13 00:11:13

有一种更好的方法来执行此操作,而不是为每个 POST 变量重复您自己的代码,但效率不高。

// 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
}

如果你想变得超级高效,你可以简单地使用:

// 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
}

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
}
流心雨 2024-10-13 00:11:13

引入变量 $sendToDb 并将其初始设置为 (bool) true。如果任何检查失败,请将此变量设置为 false。
然后重写 else-Part 并执行

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

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 */
}
看春风乍起 2024-10-13 00:11:13

获取一个标志变量并像这样检查

$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
                  }

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
                  }
甜中书 2024-10-13 00:11:13

您确实不应该将服务器端代码 (PHP) 与客户端代码 (JavaScript) 混合在一起。

首先在服务器端进行验证。然后在客户端添加验证。原因是,如果您的用户启用了 JavaScript,那么他们会在表单提交之前收到错误消息。如果他们禁用了 JavaScript,那么您的 PHP 脚本将抛出错误。类似于以下脚本:

<?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
    }
}

然后是以下模板:

<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>

这将首先通过 JavaScript 然后在服务器端将 .error 类应用于任何无效的表单字段。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文