2012-04-13 1 views
1

간단한 지정 유효성 검사,MVC3 간단한 지정 유효성 검사

내 모델 및 사용자 지정 유효성 검사 :

public class Registration 
{ 
    [Required(ErrorMessage = "Date of Birth is required")]   
    [AgeV(18,ErrorMessage="You are not old enough to register")] 
    public DateTime DateOfBirth { set; get; } 
} 

public class AgeVAttribute : ValidationAttribute 
{ 
    private int _maxAge; 

    public AgeVAttribute(int maxAge) 
    { 
     _maxAge = maxAge; 
    } 

    public override bool IsValid(object value) 
    { 
     return false;  <--- **this never gets executed.... what am I missing?** 
    } 
} 

(위의 인라인 주석을 참조하십시오)

보기 :

@using (Html.BeginForm()) { 
@Html.ValidationSummary("Errors") 
<fieldset> 
    <legend>Registration</legend> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.DateOfBirth) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.DateOfBirth)  
    </div> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
} 
+1

모델을받는 컨트롤러의 모양은 어떻습니까? –

+1

빈 MVC 프로젝트에서 코드를 시험해 본 결과, IsValid에 대한 호출이 발생합니다. – Iridio

+0

'등록'유형의 모델을 사용하는 '조치'방법을 제공하겠습니까? 귀하의 코드를 테스트했습니다, 그것은 서버 측에서 작동합니다. 'AgeVAttribute'가 IClientValidatable를 구현하지 않으므로 클라이언트 측 유효성 검사가 해제됩니다. – Kibria

답변

2

수 재보험.

모델 :

public class Registration 
{ 
    [Required(ErrorMessage = "Date of Birth is required")] 
    [AgeV(18, ErrorMessage = "You are not old enough to register")] 
    public DateTime DateOfBirth { set; get; } 
} 

public class AgeVAttribute : ValidationAttribute 
{ 
    private int _maxAge; 

    public AgeVAttribute(int maxAge) 
    { 
     _maxAge = maxAge; 
    } 

    public override bool IsValid(object value) 
    { 
     return false; 
    } 
} 

컨트롤러 :

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new Registration 
     { 
      DateOfBirth = DateTime.Now.AddYears(-10) 
     }); 
    } 

    [HttpPost] 
    public ActionResult Index(Registration model) 
    { 
     return View(model); 
    } 
} 

보기 :

@model Registration 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary("Errors") 
    <fieldset> 
     <legend>Registration</legend> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.DateOfBirth) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.DateOfBirth)  
     </div> 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

양식이 제출 될 때 IsValid 방법은 항상 맞았다. 또한 jquery.validate.jsjquery.validate.unobtrusive.js 스크립트를 포함하지 않았으므로 클라이언트 측 유효성 검사를 활성화하지 않았 음을 유의하십시오. 포함 시켰 으면 오류가 발생할 가능성이 있습니다. 클라이언트 쪽 유효성 검사를 사용하면 양식이 서버에 제출되지 않아 IsValid 메소드가 호출되지 않는 것이 정상적인 경우입니다.

+0

thx Darin, 한번 배치 한 [HttpPost] 공개 ActionResult 색인 (등록 모델) { 반환보기 (모델); } IsValid 메서드가 실행되었습니다. 어렵지 않다면, 저에게 당신이 도와 주셔서 감사 드리며 대신 클라이언트 쪽 유효성 검사를 사용하여 어떻게 확인 할 수 있는지 제게 보여주십시오. – Ben

+0

사용자 정의 유효성 검사 속성에 IClientValidatable 인터페이스를 구현 한 다음 사용자 정의 어댑터를 등록 할 수 있습니다 서버에있는 것과 동일한 유효성 검사 논리를 작성하고 복제해야하는 javascript 함수를 나타냅니다. 여기 예가 있습니다 : http://stackoverflow.com/a/4747466/29407 –

+0

안녕하세요 대린, 게시 한 예를 확인했습니다. 마지막 부분 (맞춤 어댑터 정의)이 나올 때까지 모든 것이 명확합니다. 어떻게 나이 제한 (사용자 지정 어댑터) 구현할 것이라고, 나는 예제를 볼 see.test() 메서드, 무슨 일을하고 있는지 .. 만약 당신이 나를 다시 설명 할 수있는 멋진 감사합니다. – Ben