2

사용자 지정 유효성 검사 특성을 만드는 방법을 이해했습니다. 실제로 Seed 메서드를 사용하여 데이터베이스를 미리 채울 때 Validate 메서드가 실행되고 실패하면 예외가 throw됩니다. 그러나 유효성 검사는 엔터티의 양식 만들기에서 작동하지 않습니다.CustomValidation 특성이 ASP.NET MVC 3 및 ​​EF에서 작동하지 않습니다

뭔가를 HTML (면도기 폼)으로 변경해야합니까?

유효성 검사에 실패한 항목을 추가 할 수 있습니다. 여기

코드 :

namespace Data.Model 
{ 
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 
    sealed public class YearsValidationAttribute : ValidationAttribute 
    { 
     // Internal field to hold the min value. 
     readonly int _years; 

     public int Years 
     { 
      get { return _years; } 
     } 

     public YearsValidationAttribute(int years) 
     { 
      _years = years; 
     } 


     public override bool IsValid(object value) 
     { 
      var years = (int)value; 
      bool result = true; 
      if (this.Years != null) 
      { 
       result = Years >= years; 
      } 
      return result; 
     } 



     public override string FormatErrorMessage(string name) 
     { 
      return String.Format(CultureInfo.CurrentCulture, 
       ErrorMessageString, name, Years); 
     } 
    } 
} 


public class Position 
    { 
     [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)] 
     public int PositionID { get; set; } 

     [Required(ErrorMessage = "Position name is required.")] 
     [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")] 
     [Display(Name = "Position name")]    
     public string name { get; set; } 

     [Required(ErrorMessage = "Number of years is required")] 
     [Display(Name = "Number of years")] 
     [YearsValidationAttribute(5, ErrorMessage = "{0} value must be greater than {1} years.")]   
     public int yearsExperienceRequired { get; set; } 

     public virtual ICollection<ApplicantPosition> applicantPosition { get; set; } 
    } 



@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Position</legend> 

     @Html.HiddenFor(model => model.PositionID) 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.name) 
      @Html.ValidationMessageFor(model => model.name) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.yearsExperienceRequired) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.yearsExperienceRequired) 
      @Html.ValidationMessageFor(model => model.yearsExperienceRequired) 
     </div> 

     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

답변

2

당신이 당신에게 클라이언트 검증 만 서버 측을 제공하지 않습니다이 그 코드입니다. 그러나 그것은 좋은 출발점입니다. 당신은뿐만 아니라 클라이언트 측 유효성 검사를 원하는 경우

public ActionResult YourAction(YourModel model) 
{ 
    if(ModelState.IsValid) 
    { 
     // Do your save 
    } 
    else 
    { 
     // Do your other stuff 
    } 
} 

여기에 자원을 사용할 수 있습니다 : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

당신이 서버에서 사용자의 액션 메소드 수행해야하는 모델은 같은 유효한지 확인하는 것입니다 Remote 유효성 검사 속성을 사용해 볼 수도 있습니다. http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

+0

사실 제가 여기에 붙여 넣은 코드입니다. 문제는 제가 유효성 검사를 거꾸로하고 있었고, 제가 변경했기 때문입니다. 또한 텍스트 상자 옆에 유효성 검사 메시지를 표시합니다. 하지만 클라이언트 쪽 유효성 검사도 시도해 보겠습니다. –

+1

잘 했어. "유효성 검사 거꾸로"란 무엇을 의미합니까? –

+0

결과 = 년> = 년, 올바른 방법은 결과 = 년> = 연도입니다. –

관련 문제