Displaying differnt border color if field is valid

2019-08-11 09:02发布

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.

enter image description here enter image description here

How would I do this through PHP? Here's the corresponding code

<?php
try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
    exit($e->getMessage());
}

// Post
$name = $_POST['name']; 
$username = $_POST['username']; 
$email = $_POST['email'];   
$password = $_POST['password']; 
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];

// Verifcation 
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
    echo "Complete all fields";
}

// Password match
if ($password != $password1) {
    echo $passmatch = "Passwords don't match";
}

// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $emailvalid = "Enter a  valid email";
}

// Password length
if (strlen($password) <= 6){
    echo $passlength = "Choose a password longer then 6 character";
}

if(empty($passmatch) && empty($emailvalid) && empty($passlength)) { 
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';

$query = $handler->prepare($sql);
$query->execute(array(
    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':ip' => $ip

 ));
}
?>

And my HTML form

<!DOCTYPE html>
<html lang="en">        
<body>
<div class="container">
    <form class="form-signin" role="form" action="register.php" method="post">
        <h2 class="form-signin-heading">Please sign up</h2>
        <input type="text" class="form-control" placeholder="Name"  name="name" autofocus style="border-color:#<?php   ?>;">
        <input type="text" class="form-control" placeholder="Username"  name="username" autofocus>
        <input type="text" class="form-control" placeholder="Email"  name="email" autofocus>
        <input type="password" class="form-control" placeholder="Password" name="password">
        <input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
    </form> 
</div>
</body>
</html>

So if the input satisfies the if statement how would I display the color?

标签: php html css forms
2条回答
Evening l夕情丶
2楼-- · 2019-08-11 09:37

I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.

The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:

echo "Complete all fields";
$fieldsValid = false;

border-color: <?php $fieldsValid ? 'blue' : 'red' ?>

But you need to do a full page reload for this to work. JavaScript is a better route:

document.forms[0].addEventListener("submit", function () {
    var usernameInput = document.querySelector("[name=username]");
    if (!usernameInput.value) {
        usernameInput.style.borderColor = "red";
    }
});    
查看更多
混吃等死
3楼-- · 2019-08-11 09:42

When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like

$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
    //run your form logic
    //if you have success, run your php query and then redirect
    //to your "success" page using a 302 (using a header("Location:... sort of call)
    //you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form

With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.

Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.

When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):

<!DOCTYPE html>
<html lang="en">        
  <body>

    <div class="container">

      <form class="form-signin" role="form" action="register.php" method="post">
        <h2 class="form-signin-heading">Please sign up</h2>
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Name"  name="name" autofocus style="border-color:#<?php   ?>;">
        </div>
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Username"  name="username" autofocus>
        </div>
        <div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
          <input type="text" class="form-control" placeholder="Email"  name="email" autofocus>
        </div>
        <div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
          <input type="password" class="form-control" placeholder="Password" name="password">
        </div>
        <div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
          <input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
      </form>
    </div> 
  </body>
</html>

I would recommend using a templating engine or something to separate the view from the actual code.

As for the help text, you can use something like this after the elements with errors:

<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
    <input type="text" class="form-control" />
    <span class="help-block"><?php echo $yourVariable; ?></span>
</div>

The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.

EDIT

Example page: http://content.kevincuzner.com/register.php

Example source: https://gist.github.com/kcuzner/11323907

查看更多
登录 后发表回答