我的PHP和JavaScript的知識是有限的。我在上課:)簡化php表單驗證 - 將兩個文件合併爲一個?
我有一個窗體,檢查,看看字段是不是空的;如果他們出現警報。第二個php文件然後檢查提交的表單,看看電子郵件和電話號碼是否符合參數;如果他們不這樣做,則表單不會被提交,並且新頁面上會顯示錯誤。 有沒有辦法將兩者結合?
這裏是關於contact.php代碼:
<script>
function validateForm()
{
var x=document.forms["contactform"]["companyname"].value;
var y=document.forms["contactform"]["name"].value;
var z=document.forms["contactform"]["telephone"].value;
var e=document.forms["contactform"]["email"].value;
if (x==null || x=="")
{
alert("company name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("name must be filled out");
return false;
}
if (z==null || z=="")
{
alert("telephone must be filled out");
return false;
}
if (e==null || e=="")
{
alert("email must be filled out");
return false;
}
//send
alert("Form sent.");
document.contactform.submit();
}
</script>
在第二send_form_email.php:
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(
!isset($_POST['telephone']) ||
!isset($_POST['email']))
{
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$companyname = $_POST['companyname']; // required
$name = $_POST['name']; // required
$telephone = $_POST['telephone']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // not required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[0-9.'-]+$/";
if(!preg_match($string_exp,$telephone)) {
$error_message .= 'The Phone Number you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
我真的不明白爲什麼這個被擱置,甚至是低估。這是一個非常好的問題......我不明白爲什麼有些用戶如此行事,甚至沒有留下如何改進它的評論。 – pattyd