asp.net-mvc – 使用BootstrapValidator与MVC DataAnnotations

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用BootstrapValidator与MVC DataAnnotations前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用DataAnnotations来指定我的验证规则,默认情况下,这些验证规则被添加到客户端,以便它们被jquery验证.

我想使用BootstrapValidator.js,因为我喜欢错误/成功消息呈现的方式.但是,它需要我在客户端重新定义验证规则. An article about BootstrapValidator.js可以找到.

有没有办法我可以使用DataAnnotations并在一个地方定义规则,仍然使用BootstrapValidator?

有什么想法吗?

解决方法

无需重新定义验证规则.您可以通过删除快速脚本并在MVC验证脚本之后引用它来简单地将MVC类型验证(即 Jquery Validation Plugin)与Bootstrap样式集成:
  1. $(function () {
  2. $('span.field-validation-valid,span.field-validation-error').each(function () {
  3. $(this).addClass('help-inline');
  4. });
  5.  
  6. $('.validation-summary-errors').each(function () {
  7. $(this).addClass('alert');
  8. $(this).addClass('alert-error');
  9. $(this).addClass('alert-block');
  10. });
  11.  
  12. $('form').submit(function () {
  13. if ($(this).valid()) {
  14. $(this).find('div.control-group').each(function () {
  15. if ($(this).find('span.field-validation-error').length == 0) {
  16. $(this).removeClass('error');
  17. }
  18. });
  19. }
  20. else {
  21. $(this).find('div.control-group').each(function () {
  22. if ($(this).find('span.field-validation-error').length > 0) {
  23. $(this).addClass('error');
  24. }
  25. });
  26. $('.validation-summary-errors').each(function () {
  27. if ($(this).hasClass('alert-error') == false) {
  28. $(this).addClass('alert');
  29. $(this).addClass('alert-error');
  30. $(this).addClass('alert-block');
  31. }
  32. });
  33. }
  34. });
  35.  
  36. $('form').each(function () {
  37. $(this).find('div.control-group').each(function () {
  38. if ($(this).find('span.field-validation-error').length > 0) {
  39. $(this).addClass('error');
  40. }
  41. });
  42. });
  43.  
  44. $("input[type='password'],input[type='text']").blur(function () {
  45. if ($(this).hasClass('input-validation-error') == true || $(this).closest(".control-group").find('span.field-validation-error').length > 0) {
  46. $(this).addClass('error');
  47. $(this).closest(".control-group").addClass("error");
  48. } else {
  49. $(this).removeClass('error');
  50. $(this).closest(".control-group").removeClass("error");
  51. }
  52. });
  53. });
  54.  
  55. var page = function () {
  56. //Update that validator
  57. $.validator.setDefaults({
  58. highlight: function (element) {
  59. $(element).closest(".control-group").addClass("error");
  60. },unhighlight: function (element) {
  61. $(element).closest(".control-group").removeClass("error");
  62. }
  63. });
  64. } ();

猜你在找的asp.Net相关文章