Perfect Javascript Form Validation using Regular Expressions.
Wall Script
Follow Me:
Thursday, March 05, 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
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


73 comments:

  1. 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

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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"!!!

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

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

    ReplyDelete
  6. 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.

    ReplyDelete
  7. 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.

    ReplyDelete
  8. 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?

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

    ReplyDelete
  10. 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

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

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

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

    ReplyDelete
  14. 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

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

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

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

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

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

    :) nice to know you :)

    ReplyDelete
  19. The Code Was Very Useful To me Yaar!!

    ReplyDelete
  20. 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

    ReplyDelete
  21. 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! :)

    ReplyDelete
  22. 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.

    ReplyDelete
  23. 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/

    ReplyDelete
  24. 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

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

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

    ReplyDelete
  27. 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

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

    ReplyDelete
  29. This is really helpful

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

    ReplyDelete
  30. What about Radio and Checkbox Validation boss.

    ReplyDelete
  31. good useful example - Tilak

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

    ReplyDelete
  33. very good example

    ReplyDelete
  34. good work dude....!!!working well

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

    ReplyDelete
  36. 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,

    ReplyDelete
  37. can the popup alert be better looking?

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

    ReplyDelete
  39. where is this function test?

    ReplyDelete
  40. very nice script thanks a lot to author...

    ReplyDelete
  41. Thank you friend I love this script

    ReplyDelete
  42. This is really helpful

    Thanks...!!!! :)
    Narine

    ReplyDelete
  43. Hi

    Thanks...it was very helpful

    Regards,

    ReplyDelete
  44. 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

    ReplyDelete
  45. 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.....

    ReplyDelete
  46. fantastic link..

    ReplyDelete
  47. Hi Srinivas,

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

    ReplyDelete
  48. 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=/^[]{}$/;

    ReplyDelete
  49. i owe u for these. :)

    ReplyDelete
  50. thanks a lotttttttt

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

    ReplyDelete
  52. Thanks a Million!!! You saved my time :)

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

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

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

    ReplyDelete
  56. Hi ,
    Thanks man the test method really helped alot.

    ReplyDelete
  57. 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 .???

    ReplyDelete
  58. ohhhhh beautiful i love this code

    ReplyDelete
  59. Why don't we use match instead of test?Is there any difference between them?

    ReplyDelete
  60. yes match is slow compare to test but both give same result

    ReplyDelete

Make in India