9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Thursday, March 5, 2009

Perfect Javascript Form Validation using Regular Expressions.

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
Comments
{ 68 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.

Eric Leads said...

I wrote a jQuery plugin for that. I admit it's a bit more code than what you've got there - but it's also a lot more configurable, reusable, and robust. And if you have a form with hundreds of fields to validate, my plugin will actually be smaller, because the code doesn't grow with the number of fields you add.

Uses HTML5's new required and pattern attributes.

http://ericleads.com/h5validate/

Anonymous said...

Hi All,

Please try to appreciate his work what he share with us. those work is not for them who are expert in doing all JavaScript kind of thing. Please do not think about Indian mentality grow-up and think if u r better why u r not doing such kind of thing

Anonymous said...

Musthu:
code for for loop for gender validation...pls

Anonymous said...

really good work bro.......
clean & clear code.......
using 'this' object was a thums up!!!

Sobio Darlington said...

var emailmodified = /^([\w-]+(?:\.[\w-]+)*)@([\w-]+)\.[a-z]{2,3}(?:(\.[a-z]{2,3})?)$/ this is a modified version of the email regex. This code can accept emails with the format: naija@email.com, naija123@email.co.uk. BUT NOT naija@email.co.ng.ukvar emailmodified = /^([\w-]+(?:\.[\w-]+)*)@([\w-]+)\.[a-z]{2,3}(?:(\.[a-z]{2,3})?)$/ this is a modified version of the email regex. This code can accept emails with the format: naija@email.com, naija123@email.co.uk. BUT NOT naija@email.co.ng.uk

Anonymous said...

Useful...thanks

Saurabh said...

How do validate a specific domain like -(xyz@abc.com) - we have validate abc.com by regular expresion.

Anonymous said...

This is really helpful

Thanks...!!!! :)
Rohit Nanania

Jm Redwan said...

What about Radio and Checkbox Validation boss.

Anonymous said...

good useful example - Tilak

Test said...

good

Unknown said...

can someone give me the same example but for radio and checkbox validation :)

Anonymous said...

very good example

Anonymous said...

good work dude....!!!working well

Anonymous said...

can anyone give me the same example for listbox and radio button

Anonymous said...

if i press three times space then name field will filled,and name will add into database as blank,what is the need of using regular expression like this,

harsha koda said...

can the popup alert be better looking?

harsha koda said...

can the popup alert be better looking or can you make it like the PHP version

Anonymous said...

where is this function test?

shubham said...

very nice script thanks a lot to author...

avinash said...

Thank you friend I love this script

Narine said...

This is really helpful

Thanks...!!!! :)
Narine

Anonymous said...

Hi

Thanks...it was very helpful

Regards,

jay gujarat said...

pls help me this mot run can u find any error

script type="text/javascript"
var str="sthisallthereis";
var patt1= /^[a-z]$/;
alert(patt1);
if(patt1.test(str))
{
document.write(str);
alert(str);
}
/script
thanx

Saranya Venkat said...

hi

i need to pass the size dynamically in the pattern.... like u mention
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;

i need to put

variable i which have some integer value in the place {3,20}

help me do this


thanks.....

Anonymous said...

fantastic link..

Karan Shah said...

thanks a ton, worked for me :)

hima javvadhi said...

Hi Srinivas,

Sweet, Simple with very big Clarity! :)
Lovely !

hima javvadhi said...

For phone no: var number= /^[0-9]{9,10}$/;
min 9 digits max 10 digits does this will work or we have another way to display.

for selecting timing
var settime=/^[]{}$/;

Anonymous said...

good work !!!

Anonymous said...

i owe u for these. :)

Anonymous said...

thanks a lotttttttt

Anonymous said...

Thank you vary much !! It helped me a lot..

Anonymous said...

Thanks a Million!!! You saved my time :)

Nagaraj Sn said...

hey......... thanks million! its helped me lot ..

Anonymous said...

Good for Beginners. Keep it up the Good work. God Bless You.

venki said...

nice work

Anonymous said...

if enter space in first name in this tutorial it accept the space is it prefect?

Anonymous said...

USEFUL.....

Anonymous said...

Hi ,
Thanks man the test method really helped alot.

Sumeet Mathew said...

Hey Srinivas Sir,
Thanx for sharing a such clean and point to point validation code. Can u help me in How to validate Hindi Inputs .???

Post a Comment