Posted By

ricosushi on 07/14/10


Tagged

form jquery validation


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

ricosushi
dhollifield
kairog
koyotebr
Kurt


Form validation


 / Published in: jQuery
 

URL: http://luiszuno.com/themes/watercolor/spring/contact.html

Validates a form before sending its values to a php file

  1. $(document).ready(function(){
  2.  
  3. // hide messages
  4. $("#error").hide();
  5. $("#success").hide();
  6.  
  7. // on submit...
  8. $("#send").click(function() {
  9. $("#error").hide();
  10.  
  11. //required:
  12.  
  13. //name
  14. var name = $("input#name").val();
  15. if(name == ""){
  16. $("#error").fadeIn().text("Name required.");
  17. $("input#name").focus();
  18. return false;
  19. }
  20.  
  21. // email
  22. var email = $("input#email").val();
  23. if(email == ""){
  24. $("#error").fadeIn().text("Email required");
  25. $("input#email").focus();
  26. return false;
  27. }
  28.  
  29. // web
  30. var web = $("input#web").val();
  31. if(web == ""){
  32. $("#error").fadeIn().text("Web required");
  33. $("input#web").focus();
  34. return false;
  35. }
  36.  
  37. // comments
  38. var comments = $("#comments").val();
  39.  
  40. // data string
  41. var dataString = 'name='+ name
  42. + '&email=' + email
  43. + '&web=' + web
  44. + '&comments=' + comments;
  45.  
  46. // ajax
  47. $.ajax({
  48. type:"POST",
  49. url: "send-mail.php",
  50. data: dataString,
  51. success: success()
  52. });
  53. });
  54.  
  55.  
  56. // on success...
  57. function success(){
  58. $("#success").fadeIn();
  59. $("#formMail").fadeOut();
  60. }
  61.  
  62. return false;
  63. });
  64.  
  65.  
  66.  
  67. // usage
  68. <!-- form -->
  69. <form id="formMail" action="#" method="post">
  70. <fieldset>
  71. <p>
  72. <label>Name:</label>
  73. <input name="name" id="name" type="text" />
  74. </p>
  75. <p>
  76. <label>Email:</label>
  77. <input name="email" id="email" type="text" />
  78. </p>
  79. <p>
  80. <label>Web:</label>
  81. <input name="web" id="web" type="text" />
  82. </p>
  83. <p>
  84. <label>Comments:</label>
  85. <textarea name="comments" id="comments" rows="5" cols="20" ></textarea>
  86. </p>
  87. <br/><br/>
  88. <p><input type="button" value=" " name="send" id="send" /></p>
  89. </fieldset>
  90. <p id="error">Message</p>
  91. </form>
  92. <p id="success">Thanks for your comments.</p>
  93. <!-- ENDS form -->

Report this snippet  

You need to login to post a comment.