Creating a red text box when an error occurs in the form

I need your help .. I'm trying to make the text box red when there is a form error ...

This is what I can do. But when I send to the front, I get the Undefined Index error_css in the form

 if (isset($_POST['submit'])) { 
 if (empty($_POST['username'])) {
       $error_css='background-color:red';
 }

The form

<label for="username">Username:</label>
<input id="username" type="text" value="<?php if(isset($_POST['username'])){ echo $_POST['username']; } ?>" name="username" title='Username' />

thank you for your time...

+3
source share
5 answers

Try something like this:

<?php

$username = "";
$error_css = "";

if (isset($_POST['submit'])) {
    if(isset($_POST['username']))
        $username = $_POST['username'];
    else
        $error_css='background-color:red';
}

?>

<label for="username">Username:</label>
<input id="username" type="text" value="<?php echo $username; ?>" name="username" title='Username' style="<?php echo $error_css; ?>"/>
0
source

you never set the style in the html tag, and the first if {if {}} - operations are redundant. It should be:

<label for="username">Username:</label>
    <input type="text" <?php 
        if(isset($_POST['username'])) { 
            echo 'value="'.$_POST['username'].'"'; 
        } else {
            echo 'style="background-color:red"';
        }
    ?> name="username" title='Username' >
+1
source

$error_css / .

, 2 , script , $error_css .

0
source

If you can, why not take a look at a solution like the jQuery validation plugin ? This is not a complete solution, since you still need some kind of server-side validation, but it will suit you.

0
source

The form

<label for="username">Username:</label>
<input id="username" type="text" value="<?php echo @$_POST['username']; ?>"
   name="username" title='Username' style="<?php echo @$error_css; ?>"/>
0
source

All Articles