Its_ToXiiC Its_ToXiiC - 9 months ago 71
PHP Question

Change empty input border after submission

I want to have it so if the person clicks the submit button and leaves a input / textarea empty. I want it to change the now gray border to red (Whichever input was left empty).

My current code:

if(empty($_POST['email']) ||
empty($_POST['name']) ||
empty($_POST['message']) ||
empty($_POST['pref-job']) ||
echo "<style type='text/css'>
input {
border: thin solid #e51923;
textarea {
border: thin solid #e51923;

Answer Source

You can do this with php, but a much better option is to use HTML5.

The required attribute will stop submission and highlight the field red if it is not populated.

<input type="email" name="email" required="required" />

Note that this will only function correctly with those browsers that implement HTML5, and should not be relied upon for validation. You should still validate server side. In this case, I would suggest adding a class to the input field to show that it is invalid in php - something like:

if (empty($_POST['email'])) {
    $emailClass = 'validationFailed';
} else {
    $emailClass = '';
printf('<input type="email" name="email" class="%s" />', $emailClass);

For this to work, you would also need the validationFailed class to have been defined of course - something like in your question:

.validationFailed {
    border: thin solid #e51923;