PHP多重验证

时间:2017-04-03 23:35:16

标签: php jquery html ajax

我试图让$name$email$message在一个脚本中进行验证,而不会让它们看起来像一个错误(让它们都变成红色)而不是那个实际上不正确的那个。

她是我正在使用的代码:

PHP:

<?php 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $visitors_site = $_POST['site'];
    $message = $_POST['message'];

    $email_from = 'mattmowen1@gmail.com';
    $email_subject = 'New Contact Submission';

    $to = 'matt.owen@example.com';
    $headers = "From:" . $email;
    $headers = "Contact Submission From: " . $email;
    $message1 = "Name: " . $name;
    $message2 = "\n\nEmail: " . $email;
    $message3 = "\n\nPhone: " . $phone;
    $message4 = "\n\nTheir Site: " . $visitors_site;
    $message5 = "\n\nMessage: " . $message;
    $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        mail($to, $email_subject, $email_body,$headers);
        exit(json_encode(array('error' => 0)));
    } else {
        exit(json_encode(array('error' => 1)));
    }

    if ($name == "") {
        exit(json_encode(array('error' => 1)));
    } else {
        mail($to, $email_subject, $email_body,$headers);
        exit(json_encode(array('error' => 0)));
    }
?>

AJAX脚本:

var sendEmail = function(){ 
    var url = 'main.php';
    $.ajax({
        url : url,
        type : "POST",
        dataType : "JSON",
        data : $('#contact-form').serialize(),
        success : function(response) {
            if (response.error == 0) { 
                $('#contact-form')[0].reset();
                alert('Form submitted successfully. We will contact you asap.');
            } else {
                $('#email-input').css('color', 'red');
                alert('ERROR MESSAGE');
            }
        }
    })
    return false;
}

HTML:

<div id="contact">
        <div class="container"> 
            <form id="contact-form" method="post" onsubmit="return sendEmail()">
            <h1>Contact Form</h1>
            <fieldset>
                <input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
            </fieldset>
            <fieldset>
                <input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </fieldset>
            <fieldset>
                <input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Web Site (optional)" type="url" name="site" required>
            </fieldset>
            <fieldset>
                <textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
            </fieldset>
            <fieldset>
                <button type="submit" id="contact-submit" name="submit">Submit</button>
            </fieldset>
            </form>
        </div>
</div>

2 个答案:

答案 0 :(得分:3)

只需发送一个坏元素列表,而不是一揽子错误陈述

<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $errors[] = "email";
}

if ($name == "") {
    $errors[] = "name";
}

if ($message == "") {
    $errors[] = "message";
}

if (count($errors) === 0) {
    mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...

然后在你的JS中:

    success : function(response) {
        if (response.length == 0) { 
            $('#contact-form')[0].reset();
            alert('Form submitted successfully. We will contact you asap.');
        } else {
            for (var i = 0; i < response.length; i++) {
                $('#' + response[i] + '-input').css('color', 'red');
                alert('ERROR MESSAGE');
            }
        }
    }

我的Javascript有点生疏,但应该可以解决这个问题。

请注意,<textarea>没有value属性,内容被添加为子文本节点。您还应该在PHP的所有输出上使用htmlspecialchars()来阻止XSS problems

答案 1 :(得分:0)

在你的js中:

$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}

您可以添加更多html代码,以便使用隐藏文本框显示。

if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
    $erro = 1;
    document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
    }    

在你的html中创建:

 <fieldset>
    <input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
     <input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>

使用css加强。