Search
Close this search box.
Search

Real Time Form Validation using Regular Expressions in jQuery

Listen to this article


Form-Validation-jQuery
Real-Time Form Validation

Whether you decide to create your own forms, or use a form builder plugin, a mandatory feature to include, is form validation. Form validation is the process of testing each field value on your form, against expected results.

For example, a simple client side validation includes verifying that the name field contains only letters, and not numbers or special characters; or that the email field is something similar to [email protected]. For such fields, it is obvious that you cannot use fixed strings to validate results, because let’s face it, there are no fixed set of names or email ids.

So, how would you validate such fields?

Even though, you cannot match exact values, you can test the values against expected results, using Regular Expressions.

Not a Developer? Let our experts WordPress experts help you!

Discuss Your Project

[space]

Example

Most of the time, the validation is performed on form submission. But, in this article, I will explain to you how you can perform real-time validation for form fields. We will be achieving the following:

[space]


Please Enter a Valid Name

[space]

Create a Regular Expression

A Regular Expression is simply a pattern for a set of values. You can use a regular expression, as a rule, to identify a string value. For example, if an expected field, must contain the string ‘ABC’, the regular expression for the field is “/ABC/”.

To create regular expressions for form fields such as name, email ID, and contact number, you can make use of RegExr. For the sake of an example, let’s consider that the ‘Name’ field should be 3 to 16 characters (only letters, irrespective of the case). The Regular Expression for the ‘Name’ field will be:

[pre]/^([a-zA-Z]{3,16})$/[/pre]

You need to now use this pattern to verify if the entered word matches the stated conditions.

[space]

Real-Time Form Validation Using jQuery

We will start by creating a simple form with an input field for ‘Name’ and a submit button.

<form>
<label>Name
<input class="name" type="text"  placeholder="Enter your name:" required/></label>
<p><span class="emsg hidden">Please Enter a Valid Name</span></p>
<input type="submit" value="Submit"/>
</form>

Here, we have added a hidden span element. This element contains the error message, which will be displayed if the user hasn’t entered a valid name. But at this point, the error message is hidden. We will be using jQuery to verify and display an error message.

Use jQuery for Field Validation

To add real-time validation, we would need to compare string values entered in the input field, against the pattern. If a match is found, we do not display an error. If there is a mismatch, the error message present in the span field will be displayed. We will be using the “match” function to validate the string with the regular expression.

Take a look at the below written code:

<script type="text/javascript">
$(document).ready(function(){
    var $regexname=/^([a-zA-Z]{3,16})$/;
    $('.name').on('keypress keydown keyup',function(){
             if (!$(this).val().match($regexname)) {
              // there is a mismatch, hence show the error message
                 $('.emsg').removeClass('hidden');
                 $('.emsg').show();
             }
           else{
                // else, do not display message
                $('.emsg').addClass('hidden');
               }
         });
});
</script>

And yes, let’s not leave out the CSS. It will help make the code more comprehensible.

.emsg{
    color: red;
}
.hidden {
     visibility:hidden;
}

By default the error message is hidden, using the “hidden” class. The jQuery code above validates every input value in the field against the pattern specified(regexname). If there is a mismatch, the “hidden” class is removed, thus making the error message visible. Do note of course that you can add additional classes, or modify the above classes as per your requirement.

[space]

But remember, this is only client-side validation, which is fine for most of the fields. But for sensitive information it’s always better to add server-side validation. This validation will have to be performed upon form submission.

Our WordPress developers can help you do that quickly and with 100% safety. If you want to learn more, you can discuss your project with them over a 1:1 call.

If you have any questions related to this article, or additional suggestions for fellow readers, do leave your comments, in the comment section below.

Also Read: How to Create a Real-Time Progress Bar using jQuery UI

Sagar Kale

Sagar Kale

One Response

  1. Hello, I would like to create a textbox whereby the user need to input in the +100-000 format. The first, second and fifth character is already define there. The user only input the third, forth, sixth until eight character, and must be number only.
    Can you please help and assist on how to do it using the pattern and oninput method?

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads