PHP/AJAX/Jquery注释表单验证


PHP / AJAX / Jquery Comment Form Validation

我正在创建一个基于jquery验证插件的注释表单(http://docs.jquery.com/Plugins/Validation)。我知道javascript很容易被黑客操纵,所以我想知道如何通过php进行验证,以确保评论表单不会生成大量垃圾邮件?

js直接来自验证插件。html表单直接来自JS验证插件页面。附加js如下:

  <script>
  $(document).ready(function(){
  $("#commentForm").submit(function(){
    if($("#commentForm").validate()){
        $.ajax({
            type: 'POST',
            url: 'process.php',
            data: $(this).serialize(),
            success: function(returnedData){
                alert(returnedData);
            }
        });
    }
    return false;
});
});
  </script>
<form class="cmxform" id="commentForm" method="POST" action="process.php">
   <label for="cname">Name</label>
   <input id="cname" name="name" size="25" class="required" minlength="2" />
   <label for="cemail">E-Mail</label>
   <input id="cemail" name="email" size="25"  class="required email" />
   <label for="curl">URL</label>
   <input id="curl" name="url" size="25"  class="url" value="" />
   <label for="ccomment">Your comment</label>
   <textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>
<input class="submit" type="submit" value="Submit"/>

php目前是相当标准的。不确定如何将验证与js和ajax集成:

<?php
$to      = 'sdfsadfssfasd@gmail.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com';
mail($to, $subject, $message, $headers);
print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>

谢谢你的帮助。有人评论说这是含糊的。澄清:

我知道如何使用php来验证电子邮件长度、不必要的字符等。我不明白jquery验证插件是如何通过ajax工作的。我需要知道如何配置我的php条件,以正确验证注释表单,防止垃圾邮件。

好吧,你做这件事的方式很直接。因此,您有一个submit函数,但在实际向.php文件发送请求之前,您需要验证输入。到目前为止,您的代码还不错,但您需要从validate函数开始。这可能看起来像这样(在jQuery中)。假设您的输入字段具有以下id:#input1、#input2、#input3、#input4。

    function validate()
{
    if($('#input1).val()=='' || $('#input2).val()==''|| $('#input3).val()=='' $('#input4).val()=='') return 0;
    else return 1;
}

这将是使用验证的最基本方法。如果你不想要jQuery,你可以用docoument.getElementById(老式的方法)代替$('#input1)。如果你也想让它对用户来说很好看,你可以在blur上验证每个输入字段!例如,假设用户关注第一个输入字段#input1

$('#input1).focus(function(){change the background color,add a border, or anything you want just to let the users see which input they clicked/tabbed on.}).blur(function(){check if the input is valid and if it's not display a message or anything you want.});