【问题标题】:Validate html5 form before calling php function?在调用 php 函数之前验证 html5 表单?
【发布时间】:2015-03-03 09:44:05
【问题描述】:

我目前有一个 html5 表单,里面有一个基本的文本区域,当你点击提交按钮时,会调用一个 php 脚本,将数据发送到数据库。

但是,在调用 PHP 脚本之前,我想在调用 PHP 之前对表单进行一些验证(检查它是否为空等),最好是在 javascript 中。

有什么办法可以做到吗?

谢谢。

Html5 格式:

<form action="submit.php" method="POST">
            <tr>
                <td id="textBox-back">  
                    <textarea id="rage-box" type="text" name="rage" cols="40" rows="5" maxlength="160"> </textarea>

                    <input id="submit" value="" name="submit" type="submit"/>


                </td>           

        </form>     

【问题讨论】:

  • 是吗?使用 Javascript?... Google 是您最好的朋友。
  • 您可以为此使用 required 属性。但仍然:PHP 检查是强制性的,因为不是每个浏览器都会执行检查(在 javascript 中都不会)。
  • 啊,好吧,所以有些 php 是强制性的。好的,谢谢您的回复。
  • 如果你想真正确定:是的。浏览器中的所有内容都可以由用户操作。永远不要相信任何基于用户的输入。如果用户愿意,他/她也可以禁用 javascript,因此检查将不起作用。

标签: javascript php html forms


【解决方案1】:
<script language="javascript">
   function validate(){

       //Code of validation

       return false;
    }
</script>


<form action="submit.php" method="POST" onsubmit="return validate();">
        <tr>
            <td id="textBox-back">  
                <textarea id="rage-box" type="text" name="rage" cols="40" rows="5" maxlength="160"> </textarea>

                <input id="submit" value="" name="submit" type="submit"/>


            </td>           

    </form>   

【讨论】:

  • 啊,是的,这已经奏效了。不过,我本可以花更长的时间在谷歌上搜索。感谢您的回复! +1
【解决方案2】:

您需要在提交或表单上添加一个 onclick。

var sub = document.getElementById('submit');
var tex = document.getElementById('rage-box');
sub.onclick = function(e){
  if(tex.value == ''){
     //stopping it from being sent
     e.preventDefault();
     alert('make sure everything is filled out');
  }
}

如果您在表单上添加事件,您需要:

  1. 为您的表单提供一个 ID
  2. 获取您的表单并添加 form.onsubmit = function(){};
  3. 然后只需复制匿名函数内的代码即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2016-05-17
    • 2014-01-22
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多