HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Displaying styled validation messages to user

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uservalidationdisplayingmessagesstyled

Problem

I'm new to AJAX and jQuery, and just for testing, I created this simple code. When the user enters their First Name and their Last Name it displays a message that says


Thanks for entering everything correctly!

in Bluish color, and when the user forgets to enter their First Name and their Last Name it displays an error that says


You didn't entered anything

in Red color or something similar. I know it sounds stupid, but this is just testing.

change_name.php

function displayError($error)
{
    // Display a div with a class of error, We style it using CSS
    echo "$error";
}

function displayMessage($message)
{
    // Display a div with a class of message, We style it using CSS
    echo "$message ";
}

if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
    if (empty($_POST['first_name']) && empty($_POST['last_name'])) {
        displayError('You didn\'t entered anything!');
    } else if (empty($_POST['first_name'])) {
        displayError('You didn\'t entered your first name!');
    } else if (empty($_POST['last_name'])) {
        displayError('You didn\'t entered your last name!');
    } else {
        displayMessage('Thanks for entering everything correctly!');
    }
}


JavaScript

$(document).ready(function(){
    $('#nameChange').on('submit', function (e) {

        $.ajax({
            type: 'POST', 
            url: 'ajax/change_name.php',
            data: $(this).serialize(),
            success: function(data) {
               $('.result').empty().append(data);
            }
        });

        e.preventDefault();
    });
});


index.php

```


jQuery AJAX


.message {
font-family: sans-serif;
color: #00AAE9;
font-size: 16px;
}

.error {
font-family: sans-serif;
color: #E70000;
font-size: 16px;
}




Result:

First Name:



Last Name:

Solution

Why wait until the data has gone to the server before you inform the user that their name is empty? You should be doing any processing up front that you can for performance reasons (though you'll still need to do validating from the server side for security reasons). I recommend the addition of the required attribute:



You can even use CSS to inform the user that the field contains invalid data.

input:invalid {
    border: 1px solid red;
}


Learn more: http://www.html5rocks.com/en/tutorials/forms/html5forms/

Code Snippets

<input type="text" name="first_name" required />
input:invalid {
    border: 1px solid red;
}

Context

StackExchange Code Review Q#61234, answer score: 3

Revisions (0)

No revisions yet.