2011-10-28 2 views
4

.NET에서 MVC 3의 boolean 속성에 대해 True 값을 요구하는 방법은 무엇입니까? 이다 내가 어디, 나는 여기에 MVC .net 등록 정보의 필수 속성에 대한 부울 값 True

<Required()> _ 
<DisplayName("Agreement Accepted")> _ 
Public Property AcceptAgreement As Boolean 

링크가이 클래스를

Public Class BooleanMustBeTrueAttribute Inherits ValidationAttribute 

    Public Overrides Function IsValid(ByVal propertyValue As Object) As Boolean 
     Return propertyValue IsNot Nothing AndAlso TypeOf propertyValue Is Boolean AndAlso CBool(propertyValue) 
    End Function 

End Class 

추가 추가 언젠가

죽는 경우 수정입니다 유효하지의 othewise True을 할 가치가 필요합니다 속성

<Required()> _ 
<DisplayName("Agreement Accepted")> _ 
<BooleanMustBeTrue(ErrorMessage:="You must agree to the terms and conditions")> _ 
Public Property AcceptAgreement As Boolean 
+0

나는 이것이 오래된 것을 알고있다. 그러나 당신이 당신의 해답을 해답으로 추가한다면, 나는 upvote 할 것이다 :) – JMK

답변

4

jquery 추가에 관심이있는 분은 확인 (체크 박스는 브라우저와 서버 모두 검증되도록) 그렇게 같은 BooleanMustBeTrueAttribute 클래스를 수정해야합니다 :

public class BooleanMustBeTrueAttribute : ValidationAttribute, IClientValidatable 
{ 
    public override bool IsValid(object propertyValue) 
    { 
     return propertyValue != null 
      && propertyValue is bool 
      && (bool)propertyValue; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     yield return new ModelClientValidationRule 
     { 
      ErrorMessage = this.ErrorMessage, 
      ValidationType = "mustbetrue" 
     }; 
    } 
} 

는 기본적으로, 클래스는 이제 IClientValidatable를 구현을하고, JS 해당 오류 메시지와를 반환 HTML 필드 ("mustbetrue")에 추가 될 jquery 유효성 검사 속성.

이제, JQuery와 유효성 검사, 작업 페이지로 다음 JS를 추가하기 위해서는 :

jQuery.validator.addMethod('mustBeTrue', function (value) { 
    return value; // We don't need to check anything else, as we want the value to be true. 
}, ''); 

// and an unobtrusive adapter 
jQuery.validator.unobtrusive.adapters.add('mustbetrue', {}, function (options) { 
    options.rules['mustBeTrue'] = true; 
    options.messages['mustBeTrue'] = options.message; 
}); 

참고 : ->Perform client side validation for custom attribute

나는이 대답에 사용되는 하나의 이전 코드를 기반으로

:

그리고 그게 :)

이전 JS에 대한 그 일을 기억 기본적으로, 당신은 페이지에 다음의 js 파일을 포함해야합니다

P. 실제로 작동 시키면 Scripts 폴더의 js 파일에 코드를 추가하고 모든 js 파일을 사용하여 번들을 만드는 것이 좋습니다.