How to validate input fields as the user is filling up a form with jQuery

In order to get sensible data from users via an online form, we have to validate data that we receive from them . As much as possible, we will want the data validation process to minimize frustration to our users.

We could have perform the data validation on the input fields at the point when the form is submitted. However, a better way will be to perform data validation on the input fields as the user is filling up the form. The validation process can follow such a sequence:

  1. User clicks on the input field.
  2. User fills up the input field with data.
  3. User clicks away from the input field.
  4. Data validation occurs on the input field. If there are any errors, display the error message near to the input field. Else everything proceeds as usual.

The demo scenario

For the sake of simplicity, I will illustrate this effect with two input text field. The first input text field requires a number from the user while the second one is optional. There are two error scenarios for the mandatory input:

  1. Nothing is entered. User had previously entered some correct data and for some reason, removing the data from the text field.
  2. User entered non numeric data in the input field.

The HTML code for the form

<form action="#" method="post">
	<label for="yourNumberTextField">Your number:</label>
	<input type="text" id="yourNumberTextField"/>
	<label for="optionalTextField">Optional value:</label>
	<input type="text" id="optionalTextField"/>

The HTML form is simple - Two labels and two text input fields. To facilitate DOM selection using jQuery, I had given the number input field a unique ID "yourNumberTextField".

CSS rules for our form

input[type=text] + p {
    display: inline;
    margin-left: 5px;

.errorField {
    border: 1px solid red;

.errorMessage {
    color: red;

The first rule make paragraphs appear right after our input field, instead of beneath it. In this demo, I had chosen to enclose error messages with the <p> tag.

The second rule will highlight the input field with red borders when data validation fails.

The third one will make the error message appear in red text.

Data validation logic

    // Handler for document ready event
    function () {
            // Handler for changes detected on yourNumberTextField
            function () {
                // Add a change listener to yourNumberTextField
                if ($.trim( $(this).attr('value') ) == '') {
                        '<p class="errorMessage">Please fill in a number.</p>');
                else if (!$.isNumeric($.trim($(this).attr('value')))) {
                        '<p class="errorMessage">Your input should be a number.</p>');
                else {
            } // end function()
        ); // end $('#yourNumberTextField').change
    } // end function
); // end function $(document).ready

First of all, I add a document ready handler to ensure that I add the change handler to the input field only when it is ready to be manipulated.

Inside the document ready handler, I add a change handler to the text input field - #yourNumberTextField.

Finally inside the change handler, I include the data validation logic.

$(this).attr('value') returns the new value in the input field. With this new value, the first if statement checks for emptiness while the second checks for non numeric values. When these two conditions hold true, I delegate the output of error messages to the outputErrorMessage function (discussed in the next section).

When the input is correct, the else statement will run. Inside the else statement block, $(this).removeClass('errorField') removes the errorField css rule which may had been applied on the input field. $(this).next().remove() then removes any error message which may had been added next to the input field.

Display an error message beside the input field

function outputErrorMessage($inputField, errorMessage) {
    // If there is a previous message
    if (!$ == 0) {
        // Remove the previous message
    } // end if
    // Show the error message
    // 'Highlight' the field
} // end function outputErrorMessage($inputField, errorMessage)

The if statement checks for any previous error message that may had been added next to the input field. In such a case, $ The remaining statements then shows the error message, highlights and brings focus to the input field.

Try the demo form


About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns and hopes that whatever he had written and built so far had benefited people.