Registration form validation using jQuery

by Developer 1. March 2010 05:28

Mainly we will use javascript for validating the several fields of our webpage. For example we have registration page with several fields like username, mobile number, email, date of birth and gender. We have to handle each filed validation in a different way. Here we are going to learn how to validate simple textbox, radio button and checkbox.

 

jQuery provides us simple way to validate each filed. Here I am explaining validation procedure for each filed.

Below is the code to validate our simple registration form fields.

 

<html>
    <head>
        <title>validating the registration form fields using jQuery</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#btn_submit').click(function(event) {

                //validating username
                    if ($('#user_name').val().length < 1) {
                        alert('Please enter user name');
                        $('#user_name').focus();
                        return false;
                    }
                    if (!is_username($('#user_name').val())) {
                        alert('Please enter valid user name');
                        $('#user_name').focus();
                        return false;
                    }
                    function is_username(uname) {
                        var pattern = new RegExp(/^[a-z0-9_]+$/);
                        return pattern.test(uname);
                    }

                    //validating mobile number
                    if ($('#mobile_number').val().length < 1) {
                        alert('Please enter your mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    if ((!is_mobile($('#mobile_number').val())) || ($('#mobile_number').val().length < 10)) {
                        alert('Please enter valid mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    function is_mobile(mobile) {
                        var pattern = new RegExp(/^[0-9]+$/);
                        return pattern.test(mobile);
                    }

                    //validating email address
                    if ($('#email_id').val().length < 1) {
                        alert('Please enter your Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    if (!is_email($('#email_id').val())) {
                        alert('Please enter valid Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    function is_email(emailid) {
                        var pattern = new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
                        return pattern.test(emailid);
                    }


                    //validating date of birth
                    if ($('#dob').val().length < 1) {
                        alert('Please enter your Date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    if (!is_dob($('#dob').val())) {
                        alert('Please enter valid date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    function is_dob(dob) {
                        var pattern = new RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);
                        return pattern.test(dob);
                    }

               //validating gender
               if ($("input[name='rdgender']:checked").val() != 'M' && $("input[name='rdgender']:checked").val() != 'F') {
                        alert('Please select your gender');
                        return false;
                    }

                    //validating checkbox
                    if ($('#chk_tc:checked').val() == null) {
                        alert('Please agree terms and conditions');
                        return false;
                    }

                });
            });   
        </script>
    </head>
    <body>
        <div style="margin-left:300px;">
        <label>User Name</label><input type="text" id="user_name"/><br/><br/>
        <label>Mobile Number</label><input type="text" id="mobile_number"/><br/><br/>
        <label>Email Id</label><input type="text" id="email_id"/><br/><br/>
        <label>Date Of Birth</label><input type="text" id="dob"/><br/><br/>
        <label>Gender</label>
            <table id="rdgender" border="0">
                            <tbody>
                            <tr>
                                <td>
                                    <input id="rdgender_0" name="rdgender" value="M" type="radio"/>
                                    <label for="rdgender_0">Male</label>

                                </td>
                                <td>
                                    <input id="rdgender_1" name="rdgender" value="F" type="radio"/>
                                    <label for="rdgender_1">Female</label>
                                </td>
                             </tr>
                           </tbody>
                          </table>   
            <br/><br/>           
       <input type="checkbox" id="chk_tc"/><label>I agree the Terms & Condition</label><br/><br/>
      <input type="submit" id="btn_submit" value="Submit"/>
        </div>       
    </body>
 </html>

 

In the above example we have simple registration form with several fields like username, mobile number, email, date of birth and gender. We will discuss validation procedure for each field separately.

 

In the first step we bind the our validation function for submit button through click event using  $('#btn_submit').click(function(event) {. Inside this function we define the validation methods for each filed

 

Validating the user name field:

 

                        //validating username
                    if ($('#user_name').val().length < 1) {
                        alert('Please enter user name');
                        $('#user_name').focus();
                        return false;
                    }
                    if (!is_username($('#user_name').val())) {
                        alert('Please enter valid user name');
                        $('#user_name').focus();
                        return false;
                    }
                    function is_username(uname) {
                        var pattern = new RegExp(/^[a-z0-9_]+$/);
                        return pattern.test(uname);
                    }

 

By using above code we are validating the user name filed. It is simple textbox, first we are checking whether user entered anything in the user name field or not by checking its length. After that we are restricting the user to enter only alphabetic, underscore(_) and numbers within the user name filed by passing user name field value o the RegExp(/^[a-z0-9_]+$/);

 

Validating mobile number:

 

                   //validating mobile number
                    if ($('#mobile_number').val().length < 1) {
                        alert('Please enter your mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    if ((!is_mobile($('#mobile_number').val())) || ($('#mobile_number').val().length < 10)) {
                        alert('Please enter valid mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    function is_mobile(mobile) {
                        var pattern = new RegExp(/^[0-9]+$/);
                        return pattern.test(mobile);
                    }

 

For the mobile number field, we have to allow only numbers and length should be minimum of 10. 

 

Validating Email Id:

 

                   //validating email address
                    if ($('#email_id').val().length < 1) {
                        alert('Please enter your Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    if (!is_email($('#email_id').val())) {
                        alert('Please enter valid Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    function is_email(emailid) {
                        var pattern = new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
                        return pattern.test(emailid);
                    }

 

There are some specific conditions for email id like email id must have @ and .(dot).  We are validating the Email Id by using RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);

 

Validating the date of birth:

 

                    //validating date of birth
                    if ($('#dob').val().length < 1) {
                        alert('Please enter your Date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    if (!is_dob($('#dob').val())) {
                        alert('Please enter valid date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    function is_dob(dob) {
                        var pattern = new RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);
                        return pattern.test(dob);
                    }

 

By using above code we are validating the date of birth. Date of birth must be like dd/mm/yy(day/month/year). We are validating the date of birth field by using  RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);

 

Validating the radio button (gender):

 

           //validating gender
           if ($("input[name='rdgender']:checked").val() != 'M' && $("input[name='rdgender']:checked").val() != 'F') {
                        alert('Please select your gender');
                        return false;
                    }

 

We have two radio buttons to ask user about his gender. We are validating radio buttons based on user input. We can validate radio button, that means gender field by comparing its value using $("input[name='rdgender']:checked").val(). It should be "M" or "F".

 

Validating checkbox:

 

                   //validating checkbox
                    if ($('#chk_tc:checked').val() == null) {
                        alert('Please agree terms and conditions');
                        return false;
                    }

 

At the end of your registration form, you need to have terms & conditions. User must accept your terms & conditions. Here you have checkbox, user must check the checkbox. You can validate checkbox by using its value $('#chk_tc:checked').val(). It should not be null.

 

In this way you can easily validate your registration form by using jQuery javascript functions.

 

Download source code: jQuery_form_validation.zip (36.46 kb)

Comments

4/10/2010 4:54:31 PM #

Asha Rana

Console Toolkit helps you to fix your video game consoles by opening up them very easily. I tried out with my  Super Nintendo,Nintendo 64 and I also opened my Nintendo GameCube easily with out breaking anything. I highly recommend to all who owns any type of Video game console like the ones I have or this others like DS and microsoft xbox and xbox 360 and ps3 and more. if you want clean or repair your systems and even you can repair your own cell and this tools will not be found on hard ware store and I recomend this Product Console Toolkit for all your repairs and cleaning also for upgrades.

Asha Rana

4/20/2010 1:02:13 AM #

Hassan Amorello

Hello Guru, Amazing post, keep the good job flow, i've been browsing around your site it looks really really great, thx for the informative post!

Hassan Amorello

4/20/2010 4:58:04 AM #

Runescape autominer

Hi,Cheers to the author for giving me some solid ideas

Runescape autominer

4/20/2010 5:50:50 AM #

fitflops

I definitely like this web-site very much. This is really informative and totally well done.Thanks a lot for this.Anyway I suggest you to come on my internet site too if you want.Summer season is approaching and we already have the best fitflops online shop of the net.We are experts in fitflops oasis and very competent. Best wishes again for your internet page.

fitflops

4/21/2010 3:29:20 AM #

Nona Hett

I leave a lot of comments on a lot of blogs each week - but there is one situation where I rarely leave a comment - even if the post deserves it.Good work

Nona Hett

4/22/2010 4:22:53 AM #

furniture

i usually don’t write comments on websites, but this article post encouraged me to praise your post. Thank you for the info, I will tweet your blog.

furniture

4/24/2010 8:47:23 AM #

satellite meter

Took me time to read everything, but I really enjoyed it. It proved to be Very helpful to me and I am sure to all the othervisitors here! It's always nice when you can not only be informed, but also entertained! Thanks again, Smile

satellite meter

4/28/2010 3:48:25 AM #

fitflop

I definitely love this site a lot. It is pretty informative and even surprisingly well done.Thanx a lot for it.However I suggest you to check my site too if you wish.Summer is approaching and we now have the most efficient fitflop online shop of the internet.We are specialized in fit flops and really professional. Best wishes again for your website.

fitflop

4/28/2010 11:14:11 PM #

Graciana Salchow

Browsing several blogengine.net blogs - it appears a fantastic platform. Best wishes to your web site, cheers!

Graciana Salchow

4/29/2010 7:10:33 AM #

tanzeela

i am workin in dot net(visioo studio) i am generating patient entry form
plz help me in code for search button i want to search patient through registartion num.plz do reply me

tanzeela

4/30/2010 6:27:58 AM #

Florene Schadler

You have actually created some excellent points here. I specifically appreciate the way you've been able to stick so much thought into a relatively short post (comparitively) which creates it an thoughtful publish on your subject. In my opinion, you've presented the topic in a quite thorough yet concise manner, that is genuinely useful when someone wants to get the facts without spending too a lot time searching the Internet and sifting out the noise to discover the answers to their questions. I usually get so frustrated with so numerous in the final results inside the major SE's due to the fact they normally seem to mostly be filled with filler content that often isn't extremely sensible. If you don't mind I'm going to add this post and your blog to my delicious favorites so I can share it with my family. I appear forward to coming back to read your future posts as well.

Florene Schadler

5/1/2010 2:02:54 AM #

Celine Jankowski

You have actually made some excellent points here. I particularly liked how you fit so a lot valuable data into such a concise blog post which created it truly enjoyable to read your thoughts for the topic. IMHO you put lots of excellent facts in this article without all the filler that most bloggers use just to make their posts appear longer, which is ideal for a gal like me who doesn't have considerably time cause I'm usually about the go. So numerous on the results on search engines are just unintelligible junk, it is nice to see a post that creates sense. I will definitely be adding this blog to my favorites list so I can share it with my friends. I appear forward to coming back to read your future posts also.

Celine Jankowski

5/2/2010 2:29:48 AM #

Best Mobile Deal

Interesting reading, thanks

Best Mobile Deal

5/2/2010 8:39:23 AM #

fitflops

I actually like this web-site a lot. It is pretty helpful and surprisingly well done.Thanx a lot for this.However I suggest you to check my internet site too if you wish.Summer season is coming and we now have the best fitflops online shop of the cyberspace.We are specialized in fitflops walkstar and incredibly experienced. Best wishes once again for your blog.

fitflops

5/11/2010 5:58:38 PM #

general contractor rhode island

Great read here! I appreciate you making this nice blog.

general contractor rhode island

5/14/2010 4:57:20 AM #

Everette Charbonnet

Hello i just came across your blog from Bing and been browsing around some of your entries and just wondering why you chose this BlogEngine type site? Dont you find it hard to do anything with? Also a security issue? I have looked at setting it up myself but not so sure.

Everette Charbonnet

5/16/2010 12:18:08 AM #

school desks home

great info. It was really very informative. The measure to turn everything green is a welcome measure in the era of global warming where every waste products are releasing toxic gases that pollutes the atmosphere. This Sustainable dining will receive a warm feedback from the people and hence will definitely stay for long.

school desks home

5/17/2010 1:42:54 AM #

wool money maker wow lvl 80

Hands down, Apple's app store wins by a mile. It's a huge selection of all sorts of apps vs a rather sad selection of a handful for Zune. Microsoft has plans, especially in the realm of games, but I'm not sure I'd want to bet on the future if this aspect is important to you. The iPod is a much better choice in that case.

wool money maker wow lvl 80

5/23/2010 12:18:27 PM #

Order soma

Great resource.  I really enjoyed your site!

Order soma

5/23/2010 2:57:28 PM #

contemporary table lamps

I have always been wowedat the way an ordinary observer lends so much more credence and attaches so much more importance to waking events than to those storiesin dreams... Man... is above all the plaything of his memory.

contemporary table lamps

5/24/2010 1:24:10 AM #

shades for lamps

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

shades for lamps

5/24/2010 7:06:17 PM #

4rx.com online pharmacy reviews

We definitely admired this blog. Please carry on this superb achievement. Be Back Soon!!!

4rx.com online pharmacy reviews

6/1/2010 9:13:30 AM #

Hypercom M4230

Do you have any other sites other than Registration form validation using jQuery?  Because with the world getting better, we'll see.  Because getting prepared and ready with the right stuff and a list is going to make it better, ya know?

Hypercom M4230

6/5/2010 11:04:43 AM #

Relationship Advice

I had fun reading this. I was forced to wonder if you meant you were leaning towards the feminine perspective here? :3

Relationship Advice

6/10/2010 5:07:08 AM #

online casinos

I just wanted to take a minute to say thanks for posting this. This area was on my mind recently, as a result I sincerely loved this article!

online casinos

6/10/2010 3:05:28 PM #

flash templates

I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.

flash templates

6/12/2010 8:04:29 PM #

Business Web Directory

Incredibly Wonderful Blogpost. Would you mind if I take a tiny snippets of your write-up and obviously link it for your blogposts??

Business Web Directory

6/14/2010 9:51:31 PM #

fisher price artic hero bedding set

I've been wondering about the exact same idea personally recently. Delighted to see another person on the same wavelength! Nice article.

fisher price artic hero bedding set

6/19/2010 9:33:53 AM #

fat loss 4 idiots review

I believe most people would agree with your post. I'm going to bookmark this web site so I can come back and read more posts. Keep up the great work!

fat loss 4 idiots review

6/21/2010 6:28:52 AM #

childrens chair

Easily, the post is definitely the greatest on this deserving topic. I agree with your conclusions and will thirstily look forward to your approaching updates. Saying thanks will not just be enough, for that tremendous clarity in your writing. I will instantly grab your rss feed to stay privy of any updates. Gratifying work and much success in your business enterprize!

childrens chair

6/23/2010 4:09:54 AM #

Hypercom T7Plus

Can you back up with reliable data?  Anyone know of any other blogs other than Registration form validation using jQuery?  Preparing and looking for the right data and places is important when trying to start this, right?  That's how I ended up here anyway.

Hypercom T7Plus

6/25/2010 11:48:18 AM #

p90x reviews

I have found this  blog post ,and I should say to you thank you so much for giving this article to us.

p90x reviews

6/28/2010 11:45:49 PM #

Tinnitus Remedies

Very worthwhile page.  Your blog is fairly quickly growing to be among my top features.

Tinnitus Remedies

6/29/2010 12:27:54 AM #

abercrombie

Do not share totally the post, but the argument is well established. Congratulations to the creator of the weblog

abercrombie

6/29/2010 6:16:17 AM #

Tinnitus Remedies

Magnificent blog post, plenty of useful information and facts.

Tinnitus Remedies

6/29/2010 9:20:08 AM #

abercrombie

A weblog with information very attractive, congratulations to the creator!

abercrombie

6/30/2010 9:37:00 AM #

Proven Penis Enlargement

What theme is this webpage site using? I know it is a blogging site engine web page but I�ve never seen this palette before.

Proven Penis Enlargement

7/1/2010 7:31:12 PM #

abercrombie and fitch

I all the time be a fan of this blog, I find it truly well structured. Congratulations to the creator of the website

abercrombie and fitch

7/7/2010 10:17:40 AM #

registry cleaners

Superbly written material, if only all website owners offered the same quality information as you, the internet would be a much better place. Please keep it up! Cheers.

registry cleaners

7/7/2010 12:21:08 PM #

football shirts

wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

football shirts

7/8/2010 1:43:27 PM #

top ten job interview questions

Who is the admin of this blog? I would like to trade links.  Looking at the amount of visitors that Registration form validation using jQuery gets and it'd be awesome for me to exchange links.  Would like to keep ahead of the competition and all.  And, most of my links come from web sites just like here.

top ten job interview questions

7/12/2010 8:53:20 AM #

engagement rings

It is so exciting to wear new jewelry!

engagement rings

7/16/2010 2:10:41 AM #

registry cleaners

It’s hard to find sharp bloggers on this topic, but you sound like you know what you are talking about! Thanks.

registry cleaners

7/20/2010 7:07:24 AM #

free multiboxing program

Really interesting article, I was wondering if you ever thought about doing some specific to gaming, such as MMO gaming?

free multiboxing program

7/22/2010 4:37:09 PM #

shweta verma

i have created a registration form and i am sending id and password in his email id  but how we can say he or she enter email id is valid  & how 2 use captcha

shweta verma

7/23/2010 5:42:55 AM #

Gaming

Right now I'm working on fixing my xbox because it has the RROD. I'll be linking back to this from my own blog.

Gaming

7/23/2010 5:59:56 PM #

Fun Games

Thanx guys, this is sweet!

Fun Games

7/24/2010 1:28:55 AM #

Lannie Valery

Good day, we are exciting toward obtain the newest Hasselbad Photographic camera, although we don't get any specific great examine over it. If ever you might have any kind of advice, i highly recommend you can you inform myself?

Lannie Valery

7/27/2010 1:05:50 PM #

ashwagandha

Your writing style is pretty great, do you have a medical background?

ashwagandha

7/27/2010 7:00:34 PM #

Aura Tognazzini

Do you earn decent capital from this webpage or are you doing it just for fun?

Aura Tognazzini

7/28/2010 7:30:05 AM #

e-cig

Ha, actions speak louder than words.

e-cig

7/28/2010 7:44:25 PM #

Zachery Bjorkquist

I don't believe the whole thing on that post, but you do make some very good things. I'm very interested in this subject and I myself do alot of explore as well. Anyway it was a well thoughtout plus fine read so I figured I would leave u a note. Feel free to check out my website sometime and let me know what you feel.

Zachery Bjorkquist

7/29/2010 8:26:12 AM #

exactjewelry.com

Nice information, kudos to the writer! It is good and correct. The usefulness and significance is overwhelming. Thanks again for this unbelievably powerful post and good luck!

exactjewelry.com

Add comment




  Country flag

Click to change captcha
biuquote
  • Comment
  • Preview
Loading



Page List

    Tag cloud