errors-within-labels.html 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Test for jQuery validate() plugin</title>
  6. <link rel="stylesheet" media="screen" href="css/screen.css">
  7. <script src="../lib/jquery.js"></script>
  8. <script src="../dist/jquery.validate.js"></script>
  9. <style>
  10. .cmxform fieldset p label span.error { color: red; }
  11. form.cmxform { width: 30em; }
  12. form.cmxform label {
  13. width: auto;
  14. display: block;
  15. float: none;
  16. }
  17. </style>
  18. <script>
  19. // only for demo purposes
  20. $.validator.setDefaults({
  21. submitHandler: function() {
  22. alert("submitted!");
  23. }
  24. });
  25. $().ready(function() {
  26. // validate the form when it is submitted
  27. var validator = $("#form1").validate({
  28. errorPlacement: function(error, element) {
  29. // Append error within linked label
  30. $( element )
  31. .closest( "form" )
  32. .find( "label[for='" + element.attr( "id" ) + "']" )
  33. .append( error );
  34. },
  35. errorElement: "span",
  36. messages: {
  37. user: {
  38. required: " (required)",
  39. minlength: " (must be at least 3 characters)"
  40. },
  41. password: {
  42. required: " (required)",
  43. minlength: " (must be between 5 and 12 characters)",
  44. maxlength: " (must be between 5 and 12 characters)"
  45. }
  46. }
  47. });
  48. $(".cancel").click(function() {
  49. validator.resetForm();
  50. });
  51. });
  52. </script>
  53. </head>
  54. <body>
  55. <h1 id="banner"><a href="https://jqueryvalidation.org/">jQuery Validation Plugin</a> Demo</h1>
  56. <div id="main">
  57. <p>Errors use spans placed within existing label element</p>
  58. <form method="get" class="cmxform" id="form1" action="">
  59. <fieldset>
  60. <legend>Login Form</legend>
  61. <p>
  62. <label for="user">Username</label>
  63. <input id="user" name="user" required minlength="3">
  64. </p>
  65. <p>
  66. <label for="password">Password</label>
  67. <input id="password" type="password" maxlength="12" name="password" required minlength="5">
  68. </p>
  69. <p>
  70. <input class="submit" type="submit" value="Login">
  71. </p>
  72. </fieldset>
  73. </form>
  74. <a href="index.html">Back to main page</a>
  75. </div>
  76. </body>
  77. </html>