Matt.Owen
Matt.Owen

Reputation: 391

PHP Multiple Validations

I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.

Her is the code I'm using:

PHP:

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

    $email_from = '[email protected]';
    $email_subject = 'New Contact Submission';

    $to = '[email protected]';
    $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 Script:

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>

Upvotes: 0

Views: 351

Answers (2)

miken32
miken32

Reputation: 42715

Just send back a list of bad elements, instead of a blanket error statement

<?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);
//...

Then in your 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');
            }
        }
    }

My Javascript is a bit rusty but that should do the trick.

Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.

Upvotes: 3

Jose Marques
Jose Marques

Reputation: 748

in your 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
}

You can put a bit more html code to make a hidden textbox appear using.

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";
    }    

create in your 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>

Use css to Spice up.

Upvotes: 0

Related Questions