Email validation php error

0

I am doing the validation of the email field of my form and in the part of validating the structure of the email I need a help. When I give else, I do not want it to send the information to the database, I want it to give false and show that the field is invalid and does not send the form, and that the user has to write a valid email, but when the else it sends the form, how can I change it? Here's a part of my code:

<?php            $email = array_key_exists('email', $_POST) ? $_POST['email'] : ''; ?>
                <p><label></label></br> <input type="text" name="email" id="email" placeholder="Email" class="form-control input-md" maxlength="50" value="<?php echo $email; ?>"/></p>
                <?php
        if($_POST)
         {
            $email = $_POST['email'];
            if ($email == "") {
                echo '<p style="font-family: Microsoft JhengHei Light;color:#fff;"><strong style="color:#8E0303;">Aviso:</strong> Campo não preenchido!</p>';
            }}
    ?>
    <?php
        if($_POST)
         {
            $email = $_POST['email'];
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) 
            {
                echo '<p style="font-family: Microsoft JhengHei Light;color:#fff;"><strong style="color:#8E0303;">Aviso:</strong> Email válido</p>';
            }else{
            echo"invalido";}
        }
    ?>

I want help on the other side, so I can not register the user until the field is right ...

Obs¹: In the if part, when the user places the right email and another field is incorrect, the valid email message will appear. Obs2: On top of the input there is something for when the user places the right email and another field is incorrect, it will not erase the text written in the field.

    
asked by anonymous 14.03.2017 / 18:42

2 answers

0

You have a logic error in your code. The final part starting after the first paragraph (% with%, which contains the <p></p> ) could be rewritten, without prejudice, as follows.

<?php
if (isset($_POST['email']) && !empty($_POST['email'])) {
    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        echo '<p style="font-family: Microsoft JhengHei Light;color:#fff;"><strong style="color:#8E0303;">Aviso:</strong> Email válido</p>';
    } else {
        echo"invalido";
    }
} else {
    echo '<p style="font-family: Microsoft JhengHei Light;color:#fff;"><strong style="color:#8E0303;">Aviso:</strong> Campo não preenchido!</p>';
}
    
14.03.2017 / 19:34
0

You can validate the email before sending the form to PHP using HTML. Example:

<input type="email" placeholder="Insira seu email">
    
14.03.2017 / 19:48