https://jqueryvalidation.org/documentation/

remote 使用

  1. $("#form-admin-add").validate({
  2. rules: {
  3. userName: {
  4. required: true,
  5. minlength: 2,
  6. maxlength: 16,
  7. remote: {
  8. type: "post",
  9. url: "/checkUserName",
  10. // data 默认使用的userName
  11. data: {
  12. userName: function() {
  13. return $("#userName").val();
  14. }
  15. },
  16. dataType: "html",
  17. dataFilter: function(data, type) {
  18. var data = JSON.parse(data);
  19. if (data.status == 400)
  20. return false;
  21. else
  22. return true;
  23. }
  24. }
  25. },
  26. password: {
  27. required: true,
  28. },
  29. password2: {
  30. required: true,
  31. equalTo: "#password"
  32. },
  33. sex: {
  34. required: true,
  35. },
  36. phone: {
  37. required: true,
  38. isPhone: true,
  39. },
  40. email: {
  41. required: true,
  42. email: true,
  43. },
  44. roleId: {
  45. required: true,
  46. },
  47. },
  48. success: function(label) {
  49. //正确时的样式
  50. label.text(" ").addClass("success");
  51. },
  52. messages: {
  53. userName: {
  54. required: "请输入用户名,3-16个字符(字母、数字、下划线),注册后不能更改",
  55. minlength: "用户名长度不能小于3个字符",
  56. maxlength: "用户名长度不能大于16个字符",
  57. remote: "用户名不可用"
  58. }
  59. },
  60. onkeyup: false,
  61. focusCleanup: true,
  62. success: "valid"
  63. });

自定义方法

  1. jQuery.validator.addMethod("checkname",
  2. function(value, element) {
  3. var resultval = false;
  4. var name = $("input[name='Name']").val();
  5. jQuery.ajax({
  6. type: 'post',
  7. async: false,
  8. url: '/checkname'
  9. dataType: 'json',
  10. success: function(result) {
  11. if (result.code == 0) {
  12. resultval = false;
  13. } else {
  14. resultval = true;
  15. }
  16. },
  17. error: function() {}
  18. });
  19. return resultval;
  20. }, "您的名称重复,请重新输入");
  21. //使用
  22. $("#searchForm").validate({
  23. rules: {
  24. materialCode: {
  25. checkname: true
  26. }
  27. }
  28. })