在提交之前使用php文件验证表单数据


Validating form data using a php file before submission

如何在发送之前验证表单数据?我有一个名为address.php的文件,它检查输入的数据以确保它符合要求。这是我的尝试,但它在提交时没有调用函数(我不想使用JS):

function validate(){
    include('checkaddress.php'); //checks data conforms
    if (empty($_POST['address']) && checkAddress($_POST['address']) == 0)
    {
        echo ("<fieldset><legend>Invalid Address</legend><p id='form' style='color:red;'><b>Invalid Address </b></fieldset>");
         return false;
    }
    else
    {
        return true;
    }
}

<form method="post" action="address.php">
            <fieldset>
<table style="float:center!improtant; text-align:center!important; margin-left:auto!important;margin-right:auto!important;">
                        <tr><legend>Address</legend></tr>
                <tr><td>
                <label for="email">address:</label>
                <input type="text" name="address" id="address" size="32" maxlength="128">
                        </tr></td>
                        <tr><td>
                <input type="submit" name="submit" onsubmit="return validate();" value="Submit" >
//Call function upon submit. I've tried 'onsubmit="validate();"'
                        </tr></td>
                    </table>
                </fieldset> 
             </form>

谢谢。

没有javascript是做不到的。

要用php验证它,您需要用javascript(例如$.ajax)将其发送到服务器,或者提交表单,然后用php验证。

老实说,验证客户端通常是更好的用户体验,首先使用JS。这并不意味着您不应该验证服务器端(PHP),因为您肯定应该验证。

  • HTML5具有一些内置验证。(http://www.sitepoint.com/html5-form-validation/)
  • Javascript表单验证库,让您的生活更轻松。(http://blog.revrise.com/web-form-validation-javascript-libraries/)