Thursday, 28 February 2013

JavaScript Form Validation using a Sample Registration Form


Description

In this document we have discussed JavaScript Form Validation using a sample registration form. Following pictorial shows in which field, what validation we want to impose.
JavaScript Form Validation using sample registration form

How would we set those validations

We will create JavaScript functions (one for each input field whose value is to validated) which checks whether a value submitted by user passes the validation.
All those functions are called into another function.
It sets the focus to the input field until the user supplies a valid value.
When user does so, they may proceed and can supply value to the next available field.
The later JavaScript function created is called on onsubmit event of the form.

HTML Code of the Sample Registration Form

  1. <!DOCTYPE html>  
  2. <html lang="en"><head>  
  3. <meta charset="utf-8">  
  4. <title>JavaScript Form Validation using a sample registration form</title>  
  5. <meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />  
  6. <meta name="description" content="This document is an example of JavaScript Form Validation using a sample registration form. " />  
  7. <link rel='stylesheet' href='js-form-validation.css' type='text/css' />  
  8. <script src="sample-registration-form-validation.js"></script>  
  9. </head>  
  10. <body onload="document.registration.userid.focus();">  
  11. <h1>Registration Form</h1>  
  12. <p>Use tab keys to move from one input field to the next.</p>  
  13. <form name='registration' onSubmit="return formValidation();">  
  14. <ul>  
  15. <li><label for="userid">User id:</label></li>  
  16. <li><input type="text" name="userid" size="12" /></li>  
  17. <li><label for="passid">Password:</label></li>  
  18. <li><input type="password" name="passid" size="12" /></li>  
  19. <li><label for="username">Name:</label></li>  
  20. <li><input type="text" name="username" size="50" /></li>  
  21. <li><label for="address">Address:</label></li>  
  22. <li><input type="text" name="address" size="50" /></li>  
  23. <li><label for="country">Country:</label></li>  
  24. <li><select name="country">  
  25. <option selected="" value="Default">(Please select a country)</option>  
  26. <option value="AF">Australia</option>  
  27. <option value="AL">Canada</option>  
  28. <option value="DZ">India</option>  
  29. <option value="AS">Russia</option>  
  30. <option value="AD">USA</option>  
  31. </select></li>  
  32. <li><label for="zip">ZIP Code:</label></li>  
  33. <li><input type="text" name="zip" /></li>  
  34. <li><label for="email">Email:</label></li>  
  35. <li><input type="text" name="email" size="50" /></li>  
  36. <li><label id="gender">Sex:</label></li>  
  37. <li><input type="radio" name="sex" value="Male" /><span>Male</span></li>  
  38. <li><input type="radio" name="sex" value="Female" /><span>Female</span></li>  
  39. <li><label>Language:</label></li>  
  40. <li><input type="checkbox" name="en" value="en" checked /><span>English</span></li>  
  41. <li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li>  
  42. <li><label for="desc">About:</label></li>  
  43. <li><textarea name="desc" id="desc"></textarea></li>  
  44. <li><input type="submit" name="submit" value="Submit" /></li>  
  45. </ul>  
  46. </form>  
  47. </body>  
  48. </html>  
  49.               
sample-registration-form-validation.js is the external JavaScript file which contains the JavaScript ocde used to validate the form. js-form-validation.css is the stylesheet containing styles for the form. Notice that for validation, the JavaScript function containing the code to validate is called on the onSubmit event of the form.
For the sake of demonstration, we have taken five countries only. You may add any number of countries in the list.

CSS Code of the Sample Registration Form

  1. h1 {  
  2. margin-left70px;  
  3. }  
  4. form li {  
  5. list-stylenone;  
  6. margin-bottom5px;  
  7. }  
  8.   
  9. form ul li label{  
  10. floatleft;  
  11. clearleft;  
  12. width100px;  
  13. text-alignright;  
  14. margin-right10px;  
  15. font-family:VerdanaArialHelveticasans-serif;  
  16. font-size:14px;  
  17. }  
  18.   
  19. form ul li input, select, span {  
  20. floatleft;  
  21. margin-bottom10px;  
  22. }  
  23.   
  24. form textarea {  
  25. floatleft;  
  26. width350px;  
  27. height150px;  
  28. }  
  29.   
  30. [type="submit"] {  
  31. clearleft;  
  32. margin20px 0 0 230px;  
  33. font-size:18px  
  34. }  
  35.   
  36. p {  
  37. margin-left70px;  
  38. font-weightbold;  
  39. }  
  40.               

JavaScript code for validation

JavaScript function which is called on onSubmit

This function call all other functions used for validation.
  1. function formValidation()  
  2. {  
  3. var uid = document.registration.userid;  
  4. var passid = document.registration.passid;  
  5. var uname = document.registration.username;  
  6. var uadd = document.registration.address;  
  7. var ucountry = document.registration.country;  
  8. var uzip = document.registration.zip;  
  9. var uemail = document.registration.email;  
  10. var umsex = document.registration.msex;  
  11. var ufsex = document.registration.fsex; if(userid_validation(uid,5,12))  
  12. {  
  13. if(passid_validation(passid,7,12))  
  14. {  
  15. if(allLetter(uname))  
  16. {  
  17. if(alphanumeric(uadd))  
  18. {   
  19. if(countryselect(ucountry))  
  20. {  
  21. if(allnumeric(uzip))  
  22. {  
  23. if(ValidateEmail(uemail))  
  24. {  
  25. if(validsex(umsex,ufsex))  
  26. {  
  27. }  
  28. }   
  29. }  
  30. }   
  31. }  
  32. }  
  33. }  
  34. }  
  35. return false;  
  36. }  

JavaScript function for validating userid

  1. function userid_validation(uid,mx,my)  
  2. {  
  3. var uid_len = uid.value.length;  
  4. if (uid_len == 0 || uid_len >= my || uid_len < mx)  
  5. {  
  6. alert("User Id should not be empty / length be between "+mx+" to "+my);  
  7. uid.focus();  
  8. return false;  
  9. }  
  10. return true;  
  11. }  
The code above checks whether userid input field is provided with a string of length 5 to 12 characters. If not, it displays an alert.

JavaScript function for validating password

  1. function passid_validation(passid,mx,my)  
  2. {  
  3. var passid_len = passid.value.length;  
  4. if (passid_len == 0 ||passid_len >= my || passid_len < mx)  
  5. {  
  6. alert("Password should not be empty / length be between "+mx+" to "+my);  
  7. passid.focus();  
  8. return false;  
  9. }  
  10. return true;  
  11. }  
  12.               
The above code used to validate password (it should be of length 7 to 12 characters). If not, it displays an alert.

JavaScript code for validating user name

  1. function allLetter(uname)  
  2. {   
  3. var letters = /^[A-Za-z]+$/;  
  4. if(uname.value.match(letters))  
  5. {  
  6. return true;  
  7. }  
  8. else  
  9. {  
  10. alert('Username must have alphabet characters only');  
  11. uname.focus();  
  12. return false;  
  13. }  
  14. }  
  15.               
The code above checks whether user name input field is provided with alphabates characters. If not, it displays an alert.

JavaScript code for validating user address

  1. function alphanumeric(uadd)  
  2. {   
  3. var letters = /^[0-9a-zA-Z]+$/;  
  4. if(uadd.value.match(letters))  
  5. {  
  6. return true;  
  7. }  
  8. else  
  9. {  
  10. alert('User address must have alphanumeric characters only');  
  11. uadd.focus();  
  12. return false;  
  13. }  
  14. }  
  15.               
The code above checks whether user address input field is provided with alphanumeric characters. If not, it displays an alert.

JavaScript code for validating country

  1. function countryselect(ucountry)  
  2. {  
  3. if(ucountry.value == "Default")  
  4. {  
  5. alert('Select your country from the list');  
  6. ucountry.focus();  
  7. return false;  
  8. }  
  9. else  
  10. {  
  11. return true;  
  12. }  
  13. }  
  14.               
The code above checks whether a country is selected from the given list. If not, then it displays an alert.

JavaScript code for validating ZIP code

  1. function allnumeric(uzip)  
  2. {   
  3. var numbers = /^[0-9]+$/;  
  4. if(uzip.value.match(numbers))  
  5. {  
  6. return true;  
  7. }  
  8. else  
  9. {  
  10. alert('ZIP code must have numeric characters only');  
  11. uzip.focus();  
  12. return false;  
  13. }  
  14. }  
The code above checks whether a ZIP code of numeric value. If not, it displays an alert.

JavaScript code for validating email format

  1. function ValidateEmail(uemail)  
  2. {  
  3. var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
  4. if(uemail.value.match(mailformat))  
  5. {  
  6. return true;  
  7. }  
  8. else  
  9. {  
  10. alert("You have entered an invalid email address!");  
  11. uemail.focus();  
  12. return false;  
  13. }  
  14. }  
The code above checks whether a valid email format is supplied. If not,it displays an alert.

JavaScript code for validating gender

  1. function validsex(umsex,ufsex)  
  2. {  
  3. x=0;  
  4.   
  5. if(umsex.checked)   
  6. {  
  7. x++;  
  8. if(ufsex.checked)  
  9. {  
  10. x++;   
  11. }  
  12. if(x==0)  
  13. {  
  14. alert('Select Male/Female');  
  15. umsex.focus();  
  16. return false;  
  17. }  
  18. else  
  19. {  
  20. alert('Form Successfully Submitted');  
  21. window.location.reload()  
  22. return true;}  
  23. }  
  24.               
The code above checks whether a sex is selected. If not, it displays an alert. If Male or Female is selected, it generates an alert saying that the form is successfully submitted and it reloads the form.
And here is the entire JavaScript used for validation of the form.
  1. function formValidation()  
  2. {  
  3. var uid = document.registration.userid;  
  4. var passid = document.registration.passid;  
  5. var uname = document.registration.username;  
  6. var uadd = document.registration.address;  
  7. var ucountry = document.registration.country;  
  8. var uzip = document.registration.zip;  
  9. var uemail = document.registration.email;  
  10. var umsex = document.registration.msex;  
  11. var ufsex = document.registration.fsex; if(userid_validation(uid,5,12))  
  12. {  
  13. if(passid_validation(passid,7,12))  
  14. {  
  15. if(allLetter(uname))  
  16. {  
  17. if(alphanumeric(uadd))  
  18. {   
  19. if(countryselect(ucountry))  
  20. {  
  21. if(allnumeric(uzip))  
  22. {  
  23. if(ValidateEmail(uemail))  
  24. {  
  25. if(validsex(umsex,ufsex))  
  26. {  
  27. }  
  28. }   
  29. }  
  30. }   
  31. }  
  32. }  
  33. }  
  34. }  
  35. return false;  
  36.   
  37. function userid_validation(uid,mx,my)  
  38. {  
  39. var uid_len = uid.value.length;  
  40. if (uid_len == 0 || uid_len >= my || uid_len < mx)  
  41. {  
  42. alert("User Id should not be empty / length be between "+mx+" to "+my);  
  43. uid.focus();  
  44. return false;  
  45. }  
  46. return true;  
  47. }  
  48. function passid_validation(passid,mx,my)  
  49. {  
  50. var passid_len = passid.value.length;  
  51. if (passid_len == 0 ||passid_len >= my || passid_len < mx)  
  52. {  
  53. alert("Password should not be empty / length be between "+mx+" to "+my);  
  54. passid.focus();  
  55. return false;  
  56. }  
  57. return true;  
  58. }  
  59. function allLetter(uname)  
  60. {   
  61. var letters = /^[A-Za-z]+$/;  
  62. if(uname.value.match(letters))  
  63. {  
  64. return true;  
  65. }  
  66. else  
  67. {  
  68. alert('Username must have alphabet characters only');  
  69. uname.focus();  
  70. return false;  
  71. }  
  72. }  
  73. function alphanumeric(uadd)  
  74. {   
  75. var letters = /^[0-9a-zA-Z]+$/;  
  76. if(uadd.value.match(letters))  
  77. {  
  78. return true;  
  79. }  
  80. else  
  81. {  
  82. alert('User address must have alphanumeric characters only');  
  83. uadd.focus();  
  84. return false;  
  85. }  
  86. }  
  87. function countryselect(ucountry)  
  88. {  
  89. if(ucountry.value == "Default")  
  90. {  
  91. alert('Select your country from the list');  
  92. ucountry.focus();  
  93. return false;  
  94. }  
  95. else  
  96. {  
  97. return true;  
  98. }  
  99. }  
  100. function allnumeric(uzip)  
  101. {   
  102. var numbers = /^[0-9]+$/;  
  103. if(uzip.value.match(numbers))  
  104. {  
  105. return true;  
  106. }  
  107. else  
  108. {  
  109. alert('ZIP code must have numeric characters only');  
  110. uzip.focus();  
  111. return false;  
  112. }  
  113. }  
  114. function ValidateEmail(uemail)  
  115. {  
  116. var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
  117. if(uemail.value.match(mailformat))  
  118. {  
  119. return true;  
  120. }  
  121. else  
  122. {  
  123. alert("You have entered an invalid email address!");  
  124. uemail.focus();  
  125. return false;  
  126. }  
  127. function validsex(umsex,ufsex)  
  128. {  
  129. x=0;  
  130.   
  131. if(umsex.checked)   
  132. {  
  133. x++;  
  134. if(ufsex.checked)  
  135. {  
  136. x++;   
  137. }  
  138. if(x==0)  
  139. {  
  140. alert('Select Male/Female');  
  141. umsex.focus();  
  142. return false;  
  143. }  
  144. else  
  145. {  
  146. alert('Form Succesfully Submitted');  
  147. window.location.reload()  
  148. return true;  
  149. }  
  150. }  
Download the Validation code from here.
You can view this Sample JavaScript Registration From Validation Example in a separate browser window and check how the validation is working.
We would like to hear from you regarding this document. And we welcome any constructive suggestions to improve this example.
Now, when you have finished learning how to validate a sample registration form using JavaScript, let us take you to the another way doing the same thing. But this time, the instead of on submitting the form, validations are on field level, i.e. whenever you move from one field to another. Sure that will be preety interesting to learn and share as well.

1 comment: