Posted By

tcspinks on 03/23/13


Tagged

email number input jquery validator validate


Versions (?)

Form validator


 / Published in: jQuery
 

Validate numbers only, email addresses, restricted input, required fields, and add error classes

  1. var invalidInputs = ["www", "http"]; // array of text strings not to allow in form
  2. var emailAddress = 'email'; // class for email address fields
  3. var required = 'required'; // class for required fields
  4. var error = 'error'; // class for displaying errors
  5. $(document).ready(function () {
  6.  
  7. // validate if can submit
  8.  
  9. $("form").submit(function (e) {
  10. var cancel = false;
  11. $("." + required).each(function () {
  12. if ($(this).val() === "") {
  13. $(this).addClass(error);
  14. if (!cancel) {
  15. cancel = true;
  16. $(this).focus();
  17. }
  18. }
  19. })
  20. if (cancel) e.preventDefault();
  21. });
  22.  
  23. // validate required fields on blur
  24.  
  25. $("form ." + required).blur(function() {
  26. if ($(this).val() === "") {
  27. $(this).addClass(error);
  28. } else {
  29. if ($(this).hasClass(emailAddress)) {
  30. return;
  31. }
  32. else {
  33. $(this).removeClass(error);
  34. }
  35. }
  36. })
  37.  
  38. // validate email address as it is typed
  39.  
  40. $("form ." + emailAddress).keyup(function() {
  41. var a = $("form ." + emailAddress).val();
  42. var filter = new RegExp("\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b");
  43. if ($(this).val() === "") {
  44. $(this).addClass(error);
  45. }
  46. if (filter.test(a)) {
  47. $(this).removeClass(error);
  48. return true;
  49. }
  50. else {
  51. $(this).addClass(error);
  52. return false;
  53. }
  54. });
  55.  
  56. // validate if text input is not acceptable
  57.  
  58. $("form input[type=text]").bind('blur keyup', function() {
  59. var n = invalidInputs.length;
  60. for (var i = 0; i < n; i++) {
  61. if ($(this).val().toLowerCase().indexOf(invalidInputs[i]) > -1) {
  62. $(this).addClass(error);
  63. return false;
  64. }
  65. }
  66. });
  67.  
  68. // validate numbers only
  69.  
  70. $("form .number").keydown(function (event) {
  71. if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
  72. event.keyCode == 190 || event.keyCode == 110 ||
  73. (event.keyCode == 65 && event.ctrlKey === true) ||
  74. (event.keyCode >= 35 && event.keyCode <= 39)) {
  75. return;
  76. }
  77. else {
  78. if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
  79. event.preventDefault();
  80. }
  81. }
  82. });
  83. });

Report this snippet  

You need to login to post a comment.