Loading Searchbox
9lessons programming blog logo
Thursday, March 5, 2009

Perfect Javascript Form Validation using Regular Expressions.

27 comments
I had designed a perfect form validation using javascript regular expression. Simple code and works perfect in all conditions. It's very useful and supporting all the web browsers just take a look at post live demo.

Server Side Form Validation using Regular Expressions



Download Script     Live Demo

Submit a Form without Refreshing page with jQuery and Ajax.

Name:
Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;

Learning JavaScript, 2nd Edition

Email
Standard email address
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

UserId
Supports alphabets and numbers no special characters except underscore('_') min 3 and max 20 characters.
var ck_username = /^[A-Za-z0-9_]{3,20}$/;

Password
Password supports special characters and here min length 6 max 20 charters.
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;


JavaScript Code:
You have to include this code within the tag HEAD of the page.
<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]
{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i 
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password =  /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var gender = form.gender.value;
var errors = [];
 
 if (!ck_name.test(name)) {
  errors[errors.length] = "You valid Name .";
 }
 if (!ck_email.test(email)) {
  errors[errors.length] = "You must enter a valid email 
address.";
 }
 if (!ck_username.test(username)) {
  errors[errors.length] = "You valid UserName no special 
char .";
 }
 if (!ck_password.test(password)) {
  errors[errors.length] = "You must enter a valid Password ";
 }
 if (gender==0) {
  errors[errors.length] = "Select Gender";
 }
 if (errors.length > 0) {

  reportErrors(errors);
  return false;
 }
  return true;
}
function reportErrors(errors){
 var msg = "Please Enter Valide Data...\n";
 for (var i = 0; i<errors.length; i++) {
 var numError = i + 1;
  msg += "\n" + numError + ". " + errors[i];
}
 alert(msg);
}
</script>

HTML Code
You have to modify action="#"
<form method="post" action="#" onSubmit="return validate(this);" name="form">

</form>



Download Script     Live Demo

Related Post

9lesson: Table of Contents
Sponsored Links

Recent Posts

Share this post

Subscribe to my feeds

Subscribe
Comments
27 comments
Jan Jarfalk said...

I have also found regular expressions to be very good for form validation. Therefor I created Valid8 - a Jquery plugin for form validation. It makes uses of first and foremost regexps but fall backs on ajax requests and custom javascript functions.

Its not perfect and the documentation is not finished but it certainly serves its purpoes

Check it out at http://www.unwrongest.com/projects/valid8

Luke said...

I see no reason this would need to be included in the head. There are very few occasions where js isn't better placed as far down in the body as possible.

http://developer.yahoo.com/performance/rules.html#js_bottom

Srinivas Tamada said...

Thanks Luke nice link..

Paras said...

It should not accept more then 2 dots after @. at present it's not giving error for "aa.aa@aa.cc.vv.fff.ee.tt.com.com"!!!

FrEaKmAn said...

Just a notice, some people have names which contain non-english letters. So your form is not perfect :D

Ying Yanh said...

What if I disable Javascript?

Anonymous said...

1999 called, they want their tutorial back. seriously, does anyone actually do this soft of stuff anyone now that we have jQuery?

Rob said...

As far as when it's bad to put scripts outside of the head is if your page is XHTML. Scripts outside of the head are a no-no if you want to validate. And if you have *that* much JS on your page where this is becoming a problem it might be time to think if there's anything that you're doing in the JS that can be done via simple CSS or by server side processing.

Rob said...

Anonymous - About jquery. Yes, people still need to do this. Sometimes you need a very lightweight validation tool for a web page (< 1-2K) whereas including jquery (56KB minified) and the validation plugin (16KB) is not acceptable. I agree that this is a problem that's been solved a thousand times, but as awesome as jquery is, it's sometimes a bit too "big" for a lot of cases.

László Lajos said...

It's ok, but I think regexes are not enough for a form validation. In example, what do you do, when u have to validate an integer beetween 64 and 256?

Anonymous said...

@Rob
You can choose not to believe it, but some of us still actually write our JavaScript.

Anonymous said...

what if someones name is mark o'reilly, or mark pinkett-smith ?

your script does not test for that, also 20 as max? very prosumptious that everyone only have a max of 20 chars in a name

Joe said...

May not be perfect but nothing ever is. The passion for programming is definitely there. And so I say, nice work Srinivas.

Anonymous said...

hey, why dont you try Google adsense?...

Srinivas Tamada said...

I tried google adsense but they are not accepting my site please help me...

Anonymous said...

Is there someone out there that can help me. I don't know much about javascript and it is driving me crazy as I have attempted changing the code many times. I used the one in this example but no success. The form is just submitted without validation. http://www.oasishairdesign.com/guestbook8.html

Anonymous said...

Got it to work, never mind. This code works great. Thank you very much.

Anonymous said...

Its very useful for me. Thank you very much...

kiran said...

How to Validate the email with following characters "! # $ % & ' * + - / = ? ^ _ ` { | } ~"
in java script.

Anonymous said...

nice blog btw...
sent me your unique tutorial
if you have time :)

c00l35t-5p0t-69.blogspot.com
-------------------------------

:) nice to know you :)

Rajkumar said...

The Code Was Very Useful To me Yaar!!

Anonymous said...

HI Srinivas,

Nice work and thanks for sharing. For those who think this form is not perfect, I suggest you sharing your knowledge to improving this form...as nothing can be perfect.

Cheers,

Cyril

Создание сайта said...

Thank You!

Freek said...

I really don't want to be mean about this but the main script file is full of left-over functions (recycled code ?) that are not being used anywhere and since we're talking 'light-weight' here, that kind of beats both its purpose and its 'Perfect' title.

I'd lie however, if I'd say that this didn't prove useful at all because it stood as a POC for what I needed done, so I do owe you a big THANK YOU! :)

webnet said...

Live demo don`t work

Anup @ Hack Tutors said...

This was really cool!:)

Sumit Joshi said...

Dear Friend,
You worked but I don't know, it does not work for me. Please send me working model on joshisumitnet [at] yahoo [dot] com
I am PHP developer.

waiting for your reply.

Post a Comment

Orkut | FacebookAbout Me

Subscribe now!Feeds RSS

Subscribe now!Recent Posts

Subscribe now!Categories

Subscribe now!Comments

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Join into my community

Labs ProfileRelease

My ProfileTwitter