我的 php 和 javascript 知识有限。我正在上课:)
我有一个表格可以检查字段是否为空;如果他们是警报出现。然后第二个 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._%-]+@[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);
}