Posted By

SubriseSammy on 09/30/11


Tagged

form jquery validator


Versions (?)

Form Validate


 / Published in: jQuery
 

Simple form validator

Just give your form the class validate and add the classes required or requiredEmail to the required input fields.

  1. (function($){
  2.  
  3. $(document).ready(function(){
  4.  
  5. $('form.validate').submit(function(){
  6.  
  7. var allPassed = true,
  8. msg = 'Niet alle verplichte velden zijn ingevuld, deze zijn rood gemarkeerd.',
  9. email_msg = 'Vul een geldig emailadres in aub',
  10. valid_bg = '#dff7dc',
  11. valid_bor = '1px solid #a0da9d',
  12. invalid_bg = '#e6b3b3',
  13. invalid_bor = '1px solid #bd4444';
  14.  
  15. // check if all required elements are filled in
  16. $(this).find('.required').each(function(){
  17. if ($(this).val().trim() == "")
  18. {
  19. allPassed = false;
  20. $(this).css({
  21. 'background-color' : invalid_bg,
  22. 'border' : invalid_bor
  23. });
  24. }
  25. else
  26. {
  27. $(this).css({
  28. 'background-color' : valid_bg,
  29. 'border' : valid_bor
  30. });
  31. }
  32. });
  33.  
  34. // check if requiredEmail elements are filled in
  35. $(this).find('.requiredEmail').each(function(){
  36.  
  37. if ($(this).val().trim() === "")
  38. {
  39. allPassed = false;
  40. $(this).css({
  41. 'background-color' : invalid_bg,
  42. 'border' : invalid_bor
  43. });
  44. }
  45. else
  46. {
  47. var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  48. if(reg.test($(this).val()) == false)
  49. {
  50. allPassed = false;
  51. msg = email_msg;
  52. $(this).css({
  53. 'background-color' : invalid_bg,
  54. 'border' : invalid_bor
  55. });
  56. }
  57. else
  58. {
  59. $(this).css({
  60. 'background-color' : valid_bg,
  61. 'border' : valid_bor
  62. });
  63. }
  64. }
  65. });
  66.  
  67. if ( ! allPassed )
  68. alert(msg);
  69.  
  70. return allPassed;
  71.  
  72. });
  73.  
  74. });
  75.  
  76. })(jQuery);

Report this snippet  

You need to login to post a comment.