form-validate-demo.js 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //以下为修改jQuery Validation插件兼容Bootstrap的方法,没有直接写在插件中是为了便于插件升级
  2. $.validator.setDefaults({
  3. highlight: function (element) {
  4. $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
  5. },
  6. success: function (element) {
  7. element.closest('.form-group').removeClass('has-error').addClass('has-success');
  8. },
  9. errorElement: "span",
  10. errorPlacement: function (error, element) {
  11. if (element.is(":radio") || element.is(":checkbox")) {
  12. error.appendTo(element.parent().parent().parent());
  13. } else {
  14. error.appendTo(element.parent());
  15. }
  16. },
  17. errorClass: "help-block m-b-none",
  18. validClass: "help-block m-b-none"
  19. });
  20. //以下为官方示例
  21. $().ready(function () {
  22. // validate the comment form when it is submitted
  23. $("#commentForm").validate();
  24. // validate signup form on keyup and submit
  25. var icon = "<i class='fa fa-times-circle'></i> ";
  26. $("#signupForm").validate({
  27. rules: {
  28. firstname: "required",
  29. lastname: "required",
  30. username: {
  31. required: true,
  32. minlength: 2
  33. },
  34. password: {
  35. required: true,
  36. minlength: 5
  37. },
  38. confirm_password: {
  39. required: true,
  40. minlength: 5,
  41. equalTo: "#password"
  42. },
  43. email: {
  44. required: true,
  45. email: true
  46. },
  47. topic: {
  48. required: "#newsletter:checked",
  49. minlength: 2
  50. },
  51. agree: "required"
  52. },
  53. messages: {
  54. firstname: icon + "请输入你的姓",
  55. lastname: icon + "请输入您的名字",
  56. username: {
  57. required: icon + "请输入您的用户名",
  58. minlength: icon + "用户名必须两个字符以上"
  59. },
  60. password: {
  61. required: icon + "请输入您的密码",
  62. minlength: icon + "密码必须5个字符以上"
  63. },
  64. confirm_password: {
  65. required: icon + "请再次输入密码",
  66. minlength: icon + "密码必须5个字符以上",
  67. equalTo: icon + "两次输入的密码不一致"
  68. },
  69. email: icon + "请输入您的E-mail",
  70. agree: {
  71. required: icon + "必须同意协议后才能注册",
  72. element: '#agree-error'
  73. }
  74. }
  75. });
  76. // propose username by combining first- and lastname
  77. $("#username").focus(function () {
  78. var firstname = $("#firstname").val();
  79. var lastname = $("#lastname").val();
  80. if (firstname && lastname && !this.value) {
  81. this.value = firstname + "." + lastname;
  82. }
  83. });
  84. });