我的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);
}
我将进行jQuery验证:
http://jquery.bassistance.de/validate/demo/
在数据库中输入信息或通过电子邮件发送之前,请使用trim和mysql转义字符。(PHP:http://php.net/manual/en/function.mysql-real-escape-string.php)
基本上,您可以使用jQueryValidation插件在客户端进行所有验证。
我通常使用类似jqueryForms的东西(http://malsup.com/jquery/form/)请通过ajax提交页面,并在PHP中进行所有验证,这样做的好处是,如果我需要检查emial地址是否正在使用,或者想对数据运行一些高级服务器端/数据库驱动的检查,那么我会让它返回一个json对象,然后脚本将使用该对象来抛出错误并突出显示字段等。额外的好处是,由于我已经用jqueryForms完成了所有这些,我可以通过ajax完成整个表单,并为用户提供流畅的体验。
我不是一个你可能想要的更复杂的解决方案(根据你的经验,你在实现时可能需要仔细阅读),但它只给了你一个担心验证的地方,并且不会强迫用户等待重新加载才知道提交的信息不起作用(还有额外的积分,如果有人提交了一个包含密码或captcha的for,他们就不必重新输入)。