简体   繁体   English

PHP / JavaScript表单验证?

[英]PHP/JavaScript form validation?

I'm new with PHP and JavaScript. 我是PHP和JavaScript的新手。 I eant to validate form, and if the form input fields are correct, then send it to php external script. 我想验证表单,如果表单输入字段正确,则将其发送到php外部脚本。 I've tried something like this: 我已经尝试过这样的事情:

<head>
<script type="text/javascript">
  function Validate(){
    var x=document.forms["form"]["firstname"].value;
    var y=document.forms["form"]["lastname"].value;
    var z=document.forms["form"]["age"].value;
    if(x==null || x=="") {
      alert("Input name!");
    } else if(y==null || y=="") {
      alert("Input surname!");
    } else if(z==null || z=="") {
      alert("Input age!");
    } else {
  // IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
    }
  }
</script>
</head>
<body>

  <form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
    Firstname: <input type="text" name="firstname">
    Lastname: <input type="text" name="lastname">
    Age: <input type="text" name="age">
    <input type="submit">
  </form>
</body>
</html>

Since you are not returning false from your function, the form should be being submitted anyway. 由于您没有从函数返回false,因此无论如何都应提交表单。 You can stop it from being submitted by having your validate() function return false. 您可以通过使validate()函数返回false来阻止其提交。

Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. 您的代码看起来是正确的,但事实是您可能希望在失败时return false以阻止表单提交。 When not returning false, the form will simply continue to submit. 当不返回false时,表单将继续提交。

I also think you probably meant to name your form form not forma 我也想你大概意思命名表单form不是forma

You should validate the input server-side (php), even if you did it client-side (javascript). 您应该验证输入服务器端(php),即使您在客户端(javascript)进行了验证。

You do this by checking on $_POST in validate.php: 您可以通过在validate.php中检查$_POST来做到这一点:
Quite at the beginning of your script: 在脚本开始时相当:

if (isset($_POST)) {  // form has been sent

    if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry 

        $e['firstname']='please enter a firstname!'; // prepare error-msg
    }

    if (!isset($e)) {  // no error, continue handling the data

        // write data to database etc.
    }
}

// in your form...

if (isset($e)) echo "there were errors: ". implode(',',$e);

You need to put this code: 您需要输入以下代码:

function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
  alert("Input name!");
  return false;
} else if(y==null || y=="") {
  alert("Input surname!");
  return false;
} else if(z==null || z=="") {
  alert("Input age!");
  return false;
} else {
  return true;
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM