Conditional JQuery Validate Required Field


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <script>
  2. $(document).ready(function(){
  3. $("#myform").validate({
  4. groups: {
  5. username: "fname lname"
  6. },
  7. errorPlacement: function(error, element) {
  8. if (element.attr("name") == "fname"
  9. || element.attr("name") == "lname" )
  10. error.insertAfter("#lastname");
  11. else
  12. error.insertAfter(element);
  13. },
  14. rules: {
  15. fname:{
  16. required:{
  17. depends: function(element){
  18. var status = false;
  19. if( $("#yesname:checked").val() !== undefined){
  20. var status = true;
  21. }
  22. //console.log("yesname is: "+status);
  23. return status;
  24. }
  25. }
  26. },
  27. lname:{
  28. required:{
  29. depends: function(element){
  30. var status = false;
  31. if( $("#yesname:checked").val() !== undefined){
  32. var status = true;
  33. }
  34. //console.log("yesname is: "+status);
  35. return status;
  36. }
  37. }
  38. }
  39. },
  40. debug:true
  41. })
  42. });
  43. </script>
  44. <form id="myform">
  45. <label for="name">Do you have a name?</label><br>
  46. <input type="checkbox" name="name" value="y" id="yesname">yes<br>
  47. <input type="checkbox" name="name" value="n" id="noname">no<br>
  48. <p>if you have a name give it to me!</p>
  49. <label>Your Name</label>
  50. <input name="fname" id="firstname" placeholder="first name..." />
  51. <input name="lname" id="lastname" placeholder="last name..." />
  52. <br/>
  53. <input type="submit" value="Submit"/>
  54. </form>

URL: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.