php - 提交前验证表单

标签 php javascript html

我想提交一个带有 php 变量的表单以输入到 javascript 中,问题是变量仅在发布后设置,这对于它们回显到 javascript 来说为时已晚。当然,如果我再次提交,变量已经被实现到 JavaScript 中并且它应该按预期工作。但是,我宁愿只提交一次。 有什么方法可以在提交之前验证表单吗?这是我的困境的一个例子:

<?php
      if(isset($_POST['submit'])){$name=$_POST['name'];}
?>

<html>
 <div id="message"></div>
    <form action="home.html" method="POST">
       <input type="text" name="name">
       <input type="submit" name="submit" value="conditions-met" 
              onclick=<?php if($name=="bob"){echo"start();";}?>>
    </form>
</html>

 <script type="text/javascript">

  function start(){
       document.getElementById('message').innerHTML = 'hello bob';
  return true;
}
 </script>

最佳答案

男人对你很刻薄!!

基本上,您应该使用 JavaScript 验证字段。

单击提交按钮后进行检查。成功时继续,失败时显示错误消息。

示例

<form id="myForm" onsubmit="return ValidateFields(this)" name="myForm" accept-charset="UTF-8" enctype="multipart/form-data"" action="myPhpScript.php" method="POST">

// html fields


</form>


<script>

function ValidateFields(formObject)
{

   var FieldsValid = true;

   //Validate the fields and if one of them is not valid set FieldsValid to false

if(!FieldsValid )
{
   //show an error message

return false; // Returing false will prevent the form from submitting

}

return true;// the form will be submitted
}

</script>

为了成为忍者,请阅读以下内容:

http://www.script-tutorials.com/form-validation-with-javascript-and-php/

http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml

http://www.w3schools.com/js/js_form_validation.asp

关于php - 提交前验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319855/

相关文章:

php - 如何获得 FPDF 库

php - 数组的计数给出了错误的值

javascript - 创建一个将页面初始化为特定状态的按钮

javascript - 使用 JQuery 解析带有命名空间的 xml 并适用于所有浏览器..

javascript - 在 Bootstrap 2.3.2 中创建全页宽度下拉菜单

php - Laravel Eloquent : how to list posts from different authors on a page?

php - swfupload:如何解析从 upload.php 脚本返回的数据?

html - 所有浏览器的文件上传表单样式

javascript - 绝对定位时 IE 中的工具提示闪烁

javascript - 根据用户输入显示或隐藏 div