2013-06-19 2 views
1

초보자를 MVC3로 지정하고 jquery 눈에 거슬리지 않는 유효성 검사. 내 MVC보기 모델 속성에 대한 아주 간단한 사용자 지정 문자열 유효성 검사를 달성하기 위해 노력하고 있습니다. 나는 기존의 "필수"속성이 있지만 테스트 목적을 위해 내 습관을 가지고 노는 것을 알고 있습니다. 이건 내 HTML을MVC3 사용자 지정 문자열 클라이언트 유효성 검사가 작동하지 않습니다.

jQuery.validator.unobtrusive.adapters.add('stringrequired', [], function (options) { 
    options.rules['stringrequired'] = true; 
    options.messages['stringrequired'] = options.message; 
} 
); 

jQuery.validator.addMethod('stringrequired', function (value, element, params) { 
    //problem is this method is never fired 
    if (value == undefined || value == null) 
     return false; 

    if (value.toString().length == 0) 
     return false; 

    return true; 
},''); 

입니다 :

여기
[Display(Name = "Custom Property")] 
[StringRequired(ErrorMessage="My custom error message goes here")] 
public string MyProperty { get; set; } 

내 스크립트입니다 : 여기

public class StringRequiredAttribute : ValidationAttribute, IClientValidatable 
{ 
    public override bool IsValid(object value) 
    { 
     string valueToValidate = value.ToString(); 

     if ((value == null) || (valueToValidate.IsEmpty())) 
     { 
      return false; 
     } 

     return true; 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return "formatting my custom message here..."; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
     { 
      ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), 
      ValidationType = "stringrequired" 
     }; 

     yield return rule; 
    } 
} 

뷰 모델 클래스 속성 선언입니다 : 여기

내 사용자 정의 유효성 검사기 클래스입니다 마크 업 :

<textarea cols="20" data-val="true" data-val-stringrequired="My custom message is 
displayed here" id="MyProperty" name="MyProperty" rows="2"> 
</textarea> 

나는 &이 작동하지 않는 몇 가지 이유를 들어

의 web.config

에서 "true"로 설정 UnobtrusiveJavaScriptEnabled ClientValidationEnabled있다. 도움을 주시면 감사하겠습니다. 고맙습니다!

+0

정확히 작동하지 않는 기능은 무엇입니까? 오류 메시지? 처리되지 않은 예외? – Jay

+0

@Jay'//이 메소드는 결코 해고되지 않습니다 .' – AaronLS

+0

태그를'@Html.TextAreaFor <>'로 렌더링하고 jQuery unobtrusive 라이브러리에 대한 참조를로드했는지 확인하십시오. – Jay

답변

1

나는 2 센트를 추가 할 것입니다.

데모 프로젝트를 만들고 평범하게 코드를 복사하여 붙여 넣으면 나를 위해 일했습니다. (그러나 valueToValidate.IsEmpty()에서 String.IsNullOrEmpty(valueToValidate)으로 변경해야 함). (당신이 당신을 표시하지 않은 것처럼)

는 유일한 차이점은 내보기입니다 :

@model Test.Models.MyClass 
@{ 
    ViewBag.Title = "Home Page"; 
} 
@using (Html.BeginForm("Post", "Home", FormMethod.Post)) 
{ 
    @Html.TextAreaFor(x=>x.MyProperty) 
    @Html.ValidationMessageFor(x=>x.MyProperty) 

    <input type="submit" value="submit" id="Submit" /> 
} 

확인한 다음 나는 참조 해요 : jQuery를, jQuery.Validate, jQuery.Validate.Unobtrusive (순서대로)

그리고는 마지막으로이 시간 동안 저를 도청하기 때문에이 반복이

라고 위의 자바 스크립트 유효성 검사 :

유효 확인 과 같은보기에 양식이 없으면 MVC는 올바른 유효성 검사 정보를 응답에 쓰지 않습니다.

ViewContext.FormContext = new FormContext(); 

이 검증 물건을 펌프로 MVC를 속여됩니다

기본적 부분보기의 상단에이 줄을 퍼팅 ViewContext에 더미 FormContext을 만들어 그러나이를 강제 할 수있는 방법이있다

Reference

관련 문제