16

我使用DataAnnotations指定我的驗證規則,默認情況下,這些驗證規則添加到客戶端,供他們驗證的jquery。使用BootstrapValidator MVC DataAnnotations

我想使用BootstrapValidator.js因爲我喜歡錯誤/成功消息呈現的方式。但是,它要求我在客戶端重新定義驗證規則。可以找到An article about BootstrapValidator.js

有沒有一種方法可以使用DataAnnotations並在單個地方定義規則並仍然使用BootstrapValidator?

有什麼想法?

回答

4

無需再次重新定義驗證規則。你可以簡單地通過刪除一個快速腳本集成自舉造型MVC類型的驗證(這是Jquery Validation Plugin)和你的MVC驗證腳本後繼續參考:

$(function() { 
    $('span.field-validation-valid, span.field-validation-error').each(function() { 
     $(this).addClass('help-inline'); 
    }); 

    $('.validation-summary-errors').each(function() { 
     $(this).addClass('alert'); 
     $(this).addClass('alert-error'); 
     $(this).addClass('alert-block'); 
    }); 

    $('form').submit(function() { 
     if ($(this).valid()) { 
      $(this).find('div.control-group').each(function() { 
       if ($(this).find('span.field-validation-error').length == 0) { 
        $(this).removeClass('error'); 
       } 
      }); 
     } 
     else { 
      $(this).find('div.control-group').each(function() { 
       if ($(this).find('span.field-validation-error').length > 0) { 
        $(this).addClass('error'); 
       } 
      }); 
      $('.validation-summary-errors').each(function() { 
       if ($(this).hasClass('alert-error') == false) { 
        $(this).addClass('alert'); 
        $(this).addClass('alert-error'); 
        $(this).addClass('alert-block'); 
       } 
      }); 
     } 
    }); 

    $('form').each(function() { 
     $(this).find('div.control-group').each(function() { 
      if ($(this).find('span.field-validation-error').length > 0) { 
       $(this).addClass('error'); 
      } 
     }); 
    }); 

    $("input[type='password'], input[type='text']").blur(function() { 
     if ($(this).hasClass('input-validation-error') == true || $(this).closest(".control-group").find('span.field-validation-error').length > 0) { 
      $(this).addClass('error'); 
      $(this).closest(".control-group").addClass("error"); 
     } else { 
      $(this).removeClass('error'); 
      $(this).closest(".control-group").removeClass("error"); 
     } 
    }); 
}); 

var page = function() { 
    //Update that validator 
    $.validator.setDefaults({ 
     highlight: function (element) { 
      $(element).closest(".control-group").addClass("error"); 
     }, 
     unhighlight: function (element) { 
      $(element).closest(".control-group").removeClass("error"); 
     } 
    }); 
}(); 
相關問題