Tuesday, October 09, 2012

Signup form javascript validation with regular expressions - demo and coding

Demo form with validation
* click submit to check validation

Name : *
Email : *
Subject : *
Contact : *
Message :  
   
Javascript code for signup form <script type="text/javascript"> var ck_name = /^[A-Za-z0-9 ]{1,20}$/; var ck_email= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ; var ck_subject = /^[A-Za-z0-9!@#,$%^&* -.+()_]{1,150}$/; var ck_phone = /^[0-9]{8,20}$/; function validate(form){ var name = form.name.value; var email = form.email.value; var subject = form.subject.value; var phone = form.phone.value; var errors = []; if (!ck_name.test(name)) { errors[errors.length] = "Enter Valid name"; } if (!ck_email.test(email)) { errors[errors.length] = "Enter valid email-id"; } if (!ck_subject.test(subject)) { errors[errors.length] = "Enter subject"; } if (!ck_phone.test(phone)) { errors[errors.length] = "Enter phone number"; } if (errors.length > 0) { reportErrors(errors); return false; } return true; } function reportErrors(errors){ var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } </script> Signup form html code <form method="post" name="form" onSubmit="return validate(this);"> <table width="100%" border="0" cellpadding="5"> <tr> <td width="32%" align="right"> Name :</td> <td width="4%">*</td> <td width="64%"><input class="tb6" type="text" name="name"></td> </tr> <tr> <td align="right">Email :</td> <td>*</td> <td><input class="tb6" type="text" name="email" /></td> </tr> <tr> <td align="right">Subject :</td> <td>*</td> <td><input class="tb6" type="text" name="subject" /></td> </tr> <tr> <td align="right">Contact :</td> <td>*</td> <td><input class="tb6" type="text" name="phone" /></td> </tr> <tr> <td valign="top" align="right">Message :</td> <td>&nbsp;</td> <td><textarea name="message" id="message" class="tb6" cols="30" rows="3"></textarea></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td><input type="submit" value="Submit" name="submit" id="submit"></td> </tr> </table> </form>

1 comment:

Post a Comment