所以我有一些問題得到我的驗證駐留在我的PHP動作腳本。使用onclick()事件的表單驗證
我有以下形式:
<form action="contact.php" method ="post" enctype="multipart/form-data" id="contact_form" name="contact_form">
<div class="div_input"><input name="name" type="text" value="Name: " class="input4" /></div>
<div class="div_input"><input name="phone" type="text" value="Phone: " class="input4" /></div>
<div class="div_input"><input name="email" type="text" value="E-mail: " class="input4" /></div>
<textarea name="message" cols="0" rows="0" class="textarea2" >Message: </textarea>
然後我使用的onclick()方法提交。這是我相信我的問題正在出現的地方。
<div class="link4"><span><a href="#" onclick="document.getElementById('contact_form').submit()">send</a></span></div>
<div class="link4"><span><a href="#" onclick="document.getElementById('contact_form').reset()">clear</a></span></div>
</form>
我的腳本...
<?php
$errors = '';
$myemail = '[email protected]';
$name = $phone = $email = $message ='';
$nameError = $emailError =$phoneError = $messageError = '';
if(empty($_POST['name']))
{$nameError='Name is required!';}
else
{
$name = test_input($_POST['name']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError='Only letters and white space allowed';
}
}
if(empty($_POST['email']))
{$emailError='Email is required!';}
else
{
$email = test_input($_POST['email']);
//check to make sure is a valid email format
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format!";
}
}
if(empty($_POST['phone']))
{
'Phone number is required';
}
else
{
$phone = test_input($_POST['phone']);
//Allow only digits in the phone number
if(!preg_match("/^[\d\-]+$/",$phone));
{
$phoneError = 'Phone must be only numbers and dashes';
}
}
if (empty($_POST['message']))
{
$messageError = 'Message is required!';
}
else
{
$message = test_input($_POST['message']);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Phone Number: $phone\n Message \n $message";
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
//header('Location: index-5.html');
?>
當我測試,沒有驗證運行在所有。我可以點擊發送表單爲空,並且不會出現錯誤。
我見過幾個人在他們的PHP腳本中使用javascript onclick函數和驗證問題。這可能嗎?或者我在腳本或表單中丟失了什麼?我想也許我需要在submit()方法後添加一些javascript。
你們都在想什麼?
嘗試'print_r($ _ POST);'在PHP代碼的起始行 –
您的電子郵件正則表達式不正確。模擬HTML輸入按鈕(提交/重置)的方式也很糟糕。你不應該寫這樣的代碼。 – Mark
謝謝@RainFromHeaven,我會研究正則表達式。你能否詳細說明我應該如何正確操作輸入按鈕,以及對於我們這些像我這樣頭腦厚重的人來說,你的意思是什麼? – Braden