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
Server Side Form Validation using Regular Expressions
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
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>
</form>
Related Post
9lesson: Table of Contents
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.
ReplyDeleteIts not perfect and the documentation is not finished but it certainly serves its purpoes
Check it out at http://www.unwrongest.com/projects/valid8
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.
ReplyDeletehttp://developer.yahoo.com/performance/rules.html#js_bottom
Thanks Luke nice link..
ReplyDeleteIt should not accept more then 2 dots after @. at present it's not giving error for "[email protected]"!!!
ReplyDeleteJust a notice, some people have names which contain non-english letters. So your form is not perfect :D
ReplyDeleteWhat if I disable Javascript?
ReplyDeleteYou must add Server side Validations...
Delete1999 called, they want their tutorial back. seriously, does anyone actually do this soft of stuff anyone now that we have jQuery?
ReplyDeleteAs 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.
ReplyDeleteAnonymous - 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.
ReplyDeleteIt'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?
ReplyDelete@Rob
ReplyDeleteYou can choose not to believe it, but some of us still actually write our JavaScript.
what if someones name is mark o'reilly, or mark pinkett-smith ?
ReplyDeleteyour script does not test for that, also 20 as max? very prosumptious that everyone only have a max of 20 chars in a name
May not be perfect but nothing ever is. The passion for programming is definitely there. And so I say, nice work Srinivas.
ReplyDeletehey, why dont you try Google adsense?...
ReplyDeleteI tried google adsense but they are not accepting my site please help me...
ReplyDeleteIs 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
ReplyDeleteGot it to work, never mind. This code works great. Thank you very much.
ReplyDeleteIts very useful for me. Thank you very much...
ReplyDeleteHow to Validate the email with following characters "! # $ % & ' * + - / = ? ^ _ ` { | } ~"
ReplyDeletein java script.
nice blog btw...
ReplyDeletesent me your unique tutorial
if you have time :)
c00l35t-5p0t-69.blogspot.com
-------------------------------
:) nice to know you :)
The Code Was Very Useful To me Yaar!!
ReplyDeleteHI Srinivas,
ReplyDeleteNice 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
Thank You!
ReplyDeleteI 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.
ReplyDeleteI'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! :)
Live demo don`t work
ReplyDeleteThis was really cool!:)
ReplyDeleteDear Friend,
ReplyDeleteYou 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.
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.
ReplyDeleteUses HTML5's new required and pattern attributes.
http://ericleads.com/h5validate/
Hi All,
ReplyDeletePlease 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
Musthu:
ReplyDeletecode for for loop for gender validation...pls
really good work bro.......
ReplyDeleteclean & clear code.......
using 'this' object was a thums up!!!
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: [email protected], [email protected]. BUT NOT [email protected] 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: [email protected], [email protected]. BUT NOT [email protected]
ReplyDeleteUseful...thanks
ReplyDeleteHow do validate a specific domain like -([email protected]) - we have validate abc.com by regular expresion.
ReplyDeleteThis is really helpful
ReplyDeleteThanks...!!!! :)
Rohit Nanania
What about Radio and Checkbox Validation boss.
ReplyDeletegood useful example - Tilak
ReplyDeletegood
ReplyDeletecan someone give me the same example but for radio and checkbox validation :)
ReplyDeletevery good example
ReplyDeletegood work dude....!!!working well
ReplyDeletecan anyone give me the same example for listbox and radio button
ReplyDeleteif 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,
ReplyDeletecan the popup alert be better looking?
ReplyDeletecan the popup alert be better looking or can you make it like the PHP version
ReplyDeletewhere is this function test?
ReplyDeletevery nice script thanks a lot to author...
ReplyDeleteThank you friend I love this script
ReplyDeleteThis is really helpful
ReplyDeleteThanks...!!!! :)
Narine
Hi
ReplyDeleteThanks...it was very helpful
Regards,
pls help me this mot run can u find any error
ReplyDeletescript type="text/javascript"
var str="sthisallthereis";
var patt1= /^[a-z]$/;
alert(patt1);
if(patt1.test(str))
{
document.write(str);
alert(str);
}
/script
thanx
hi
ReplyDeletei 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.....
fantastic link..
ReplyDeletethanks a ton, worked for me :)
ReplyDeleteHi Srinivas,
ReplyDeleteSweet, Simple with very big Clarity! :)
Lovely !
For phone no: var number= /^[0-9]{9,10}$/;
ReplyDeletemin 9 digits max 10 digits does this will work or we have another way to display.
for selecting timing
var settime=/^[]{}$/;
good work !!!
ReplyDeletei owe u for these. :)
ReplyDeletethanks a lotttttttt
ReplyDeleteThank you vary much !! It helped me a lot..
ReplyDeleteThanks a Million!!! You saved my time :)
ReplyDeletehey......... thanks million! its helped me lot ..
ReplyDeleteGood for Beginners. Keep it up the Good work. God Bless You.
ReplyDeletenice work
ReplyDeleteif enter space in first name in this tutorial it accept the space is it prefect?
ReplyDeleteUSEFUL.....
ReplyDeleteHi ,
ReplyDeleteThanks man the test method really helped alot.
Hey Srinivas Sir,
ReplyDeleteThanx for sharing a such clean and point to point validation code. Can u help me in How to validate Hindi Inputs .???
oohhh beautiful
ReplyDeleteohhhhh beautiful i love this code
ReplyDeleteWhy don't we use match instead of test?Is there any difference between them?
ReplyDeletethank u sir love u
ReplyDeleteyes match is slow compare to test but both give same result
ReplyDeletecan you give me m ans that
ReplyDeletePin: {
type: String,
regExp:^\d{5}$
}
how to fix the length that Pin stuck after 5digits
wow.. nice code
ReplyDeleteThank you !
ReplyDelete