Email validation php error

Asked

Viewed 322 times

0

I am validating the email field of my form and in order to validate the e-mail structure I need help. When it does, I don’t want it to send the information to the database, I want it to give false and show that the field is invalid and not send the form, and that the user has to write a valid email, but when from Else it sends the form, how can I change it ? Follow 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 a help on the part of Else, not to be able to register the user until the field is right...

Note: In the if part, when the user puts the right email and another field is incorrect, the valid email message will appear. Obs²:On top of the input there is something for when the user put the right email and any other field is incorrect, will not delete the text written in the field.

2 answers

0


There is a logic error in your code. The final part that starts after the first paragraph (<p></p>, containing the <input...>) 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>';
}
  • Good answer, just a hint when you use empty doesn’t need isset ;), can also be used isset($_POST['email']{0}), would be similar to empty, but to use {0} php5.3 is required+.

0

You can validate the email before you even send the form to PHP using HTML. Example:

<input type="email" placeholder="Insira seu email">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.