skip to Main Content

I have an input box for email. i wrote code thats supposed verify that there’s no error with the email, and if there is, change the input box’s border colour to red. it dosent work. heres the code:

<?php
$emailError = false;

if (isset($_POST['submit_button'])) {
    $email = $_POST['email'];
    
    if (empty($email)||!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailError = true;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post">
            <div class="input-group" id="email-input">
                <input type="text" id="email" name="email" autocomplete="off" placeholder="Email"
                <?php
                 if ($emailError) {
                    echo "<style> #email {border-color: #ff0000;} </style>";}    
                ?>>
            </div>
            <button id="submit-button" name="submit-button" type="submit">Sign Up!</button>
        </form>
    </body>
</html>

2

Answers


  1. Add the style directly on your input:

    <input style="<?= $emailError ? 'border-color: #ff0000;' : '' ?>" type="text" id="email" name="email" autocomplete="off" placeholder="Email" />
                    
    

    Or better yet, just add a class="someClass" and define your style in a CSS file.

    .redBorder {
        border-color: #ff0000
    }
    
    <input class="<?= $emailError ? 'redBorder' : '' ?>" type="text" id="email" name="email" autocomplete="off" placeholder="Email"" />
    
    Login or Signup to reply.
  2. altered method for the above code; to work as expected: Use inline style attribute for dynamic

    <?php
    $emailError = false;
    
    if (isset($_POST['submit_button'])) {
        $email = $_POST['email'];
        
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailError = true;
        }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
        <form method="post">
            <div class="input-group" id="email-input">
                <input type="text" id="email" name="email" autocomplete="off" placeholder="Email" <?php echo $emailError ? 'style="border-color: #ff0000;"' : ''; ?>>
            </div>
            <button id="submit-button" name="submit_button" type="submit">Sign Up!</button>
        </form>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search