2016-12-17 2 views
2

別のプロパティの値に基づいてデータアノテーションを使用してプロパティを検証する必要があります。MVCで選択した値をドロップダウンしてカスタム検証を行います

私は人々が

 public class People 
     { 
      [DisplayName("Your Name")] 
      [Required] 
      public string Name { get; set; } 
      [Required] 
      public string Gender { get; set; }  
      [DisplayName("Your Age")] 
      [Required] 
      // Another Attribute here for my custom validation 
      public int Age { get; set; }    

     } 

をmodel--とキーワードがあります。

public ActionResult Index() 
     { 
      IList<SelectListItem> types = new List<SelectListItem>();   
      types.Add(new SelectListItem() { Text = "Male", Value = "M" }); 
      types.Add(new SelectListItem() { Text = "Female", Value = "F" }); 
      ViewBag.ItemTypes = types; 

      return View(); 
     } 

「性別」が、私は「年齢を検証するドロップダウンリストにバインドされ、選択した性別に基づいています'プロパティ。男性が選択されている場合は

  • その後、年齢範囲は、カスタムが存在しなければならない女性が選択されている場合は、年齢範囲は18と58

の間でなければなりません22と60

  • 間でなければなりません。このための検証属性ですが、私はそれを把握することができません。

    マイビュー:

    @using (Html.BeginForm("Index", "Test", FormMethod.Post)) 
    { 
        @Html.AntiForgeryToken() 
    
        <div class="form-horizontal"> 
         <h4>TimeRecord</h4> 
         <hr /> 
         @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
         <div class="form-group"> 
          @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" }) 
          <div class="col-md-10"> 
           @Html.DropDownListFor(model => model.Gender, (IEnumerable<SelectListItem>)ViewBag.ItemTypes, new { @class = "form-control" }) 
          </div> 
         </div> 
         <div class="form-group"> 
          @Html.LabelFor(m => m.Name, new { @class = "control-label col-md-2" }) 
          <div class="col-md-10"> 
           @Html.TextBoxFor(m => m.Name, new { @class = "form-control" }) 
           @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" }) 
          </div> 
         </div> 
    
         <div class="form-group"> 
          @Html.LabelFor(m => m.Age, new { @class = "control-label col-md-2" }) 
          <div class="col-md-10"> 
           @Html.TextBoxFor(m => m.Age, new { @class = "form-control" }) 
           @Html.ValidationMessageFor(m => m.Age, "", new { @class = "text-danger" }) 
          </div> 
         </div> 
    
    
         <div class="form-group"> 
          <div class="col-md-offset-2 col-md-10"> 
           <input type="submit" value="Create" class="btn btn-default" /> 
          </div> 
         </div> 
    
        </div> 
    } 
    
  • +0

    あなたがあなた自身の条件の検証属性を記述する必要があります。 [ASP.NET MVC 3での検証の完全ガイド - 第2部](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc- 3部-2)、クライアント側とサーバー側の両方の検証用の検証属性を作成するための良いガイドです。 –

    答えて

    0

    お客様の要件に基づき、解決策がこのようになる可能性があります。

    サーバー側の検証では、独自のカスタム側の検証属性を作成します。クライアント側の検証を有効にするには、 'IClientValidatable'を継承します。

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)] 
    public class AgeForGenderAttribute : ValidationAttribute, IClientValidatable 
    { 
        private string _PropertyToCompare { get; set; } 
        private string CurrentPropertyValue { get; set; } 
        public int _MinAgeForMale { get; set; } 
        public int _MaxAgeForMale { get; set; } 
        public int _MinAgeForFemale { get; set; } 
        public int _MaxAgeForFemale { get; set; } 
        string relevantErrorMessage { get; set; } 
    
        public AgeForGenderAttribute(string PropertyToCompare, int MinAgeForMale, int MaxAgeForMale, int MinAgeForFemale, int MaxAgeForFemale, string validationMessage) 
        { 
         this._PropertyToCompare = PropertyToCompare; 
         this._MinAgeForMale = MinAgeForMale; 
         this._MaxAgeForMale = MaxAgeForMale; 
         this._MinAgeForFemale = MinAgeForFemale; 
         this._MaxAgeForFemale = MaxAgeForFemale; 
         ErrorMessage = validationMessage; 
        } 
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
        { 
         var comparePropertyInfo = validationContext.ObjectType.GetProperty(_PropertyToCompare); 
         object dependentPropertyValue = comparePropertyInfo.GetValue(validationContext.ObjectInstance, null); 
         CurrentPropertyValue = dependentPropertyValue.ToString(); 
         var currentValue = (int)value; 
         if (dependentPropertyValue != null) 
         { 
          switch (CurrentPropertyValue) 
          { 
           case "M": 
            if (currentValue < _MinAgeForMale || currentValue > _MaxAgeForMale) 
            { 
             ErrorMessage = string.Format(ErrorMessage, _MinAgeForMale, _MaxAgeForMale); 
             return new ValidationResult(ErrorMessage); 
            } 
            break; 
           case "F": 
            if (currentValue < _MinAgeForFemale || currentValue > _MaxAgeForFemale) 
            { 
             ErrorMessage = string.Format(ErrorMessage, _MinAgeForMale, _MaxAgeForMale); 
             return new ValidationResult(ErrorMessage); 
            } 
            break; 
          } 
         } 
    
         return ValidationResult.Success; 
        } 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
        { 
         var rules = new ModelClientValidationRule 
         { 
          ValidationType = "conditionalrange", 
          ErrorMessage = ErrorMessage 
         }; 
    
         rules.ValidationParameters.Add("condiotionalpropertyname", _PropertyToCompare); 
         rules.ValidationParameters.Add("minageformale", _MinAgeForMale); 
         rules.ValidationParameters.Add("maxageformale", _MaxAgeForMale); 
         rules.ValidationParameters.Add("minageforfemale", _MinAgeForFemale); 
         rules.ValidationParameters.Add("maxageforfemale", _MaxAgeForFemale); 
         yield return rules; 
        } 
    
    } 
    

    あなたのJS:

    $(function() { 
    
        $.validator.addMethod("conditionalrange", function (value, element, params) { 
         var condiotionalpropertyname = $('#' + params.condiotionalpropertyname).val(); 
         var retVal = true; 
         switch (condiotionalpropertyname) { 
          case 'M': 
           if (value < params.minageformale || value > params.maxageformale) { 
            retVal = false; 
           } 
           break; 
          case "F": 
           if (value < params.minageforfemale || value > params.maxageforfemale) { 
            retVal = false; 
           } 
           break; 
         }  
    
         return retVal; 
        }); 
    
        $.validator.unobtrusive.adapters.add("conditionalrange", ['condiotionalpropertyname', 'minageformale', 'maxageformale', 'minageforfemale', 'maxageforfemale'], 
        function (options) { 
         options.rules['conditionalrange'] = { 
          condiotionalpropertyname: options.params.condiotionalpropertyname, 
          minageformale: options.params.minageformale, 
          maxageformale: options.params.maxageformale, 
          minageforfemale: options.params.minageforfemale, 
          maxageforfemale: options.params.maxageforfemale 
         }; 
         options.messages['conditionalrange'] = options.message; 
        } 
        ); 
    }(jQuery)); 
    

    それはまさにあなたが関連するすべてのJSが含まれていることを確認してくださいあなたのrequirement.Makeあたりとして動作します。

    プロパティ:

     [DisplayName("Your Age")] 
         [Required] 
         [AgeForGender("Gender", 18, 45, 22, 60, "Age should be between {0} and {1}")] 
         public int Age { get; set; } 
    
    +0

    ありがとう!!私にチェックさせてください。 –

    +0

    あなたの答えに応じてプロパティを飾る方法。 –

    +0

    私の答えを更新しました。 – Anadi

    2

    あなたはそれが個々のプロパティ(個々のプロパティレベルの検証)を検証するためにうまく機能として、カスタム検証属性を作成するには、以下のコードスニペットを確認することができます。

    namespace SO.Models 
    { 
        using Helpers; 
        using System.ComponentModel; 
        using System.ComponentModel.DataAnnotations; 
    
        public class Person 
        { 
         // code omitted for brevity 
    
         [DisplayName("Your Age")] 
         [Required] 
         [PersonAge(minMaleAge: 22, maxMaleAge: 60, minFemaleAge: 18, maxFemaleAge: 58)] 
         public int Age { get; set; } 
        } 
    } 
    
    namespace SO.Helpers 
    { 
        using Models; 
        using System.ComponentModel.DataAnnotations; 
    
        public class PersonAgeAttribute : ValidationAttribute 
        { 
         private const string _validationMessage = "Age should be between {0} and {1}"; 
    
         private int _minMaleAge; 
    
         private int _maxMaleAge; 
    
         private int _minFemaleAge; 
    
         private int _maxFemaleAge; 
    
         public PersonAgeAttribute(int minMaleAge, int maxMaleAge, int minFemaleAge, int maxFemaleAge) 
         { 
          _minMaleAge = minMaleAge; 
          _maxMaleAge = maxMaleAge; 
          _minFemaleAge = minFemaleAge; 
          _maxFemaleAge = maxFemaleAge; 
         } 
    
         protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
         { 
          Person person = (Person)validationContext.ObjectInstance; 
    
          if (person.Gender == "M" && (person.Age < _minMaleAge || person.Age > _maxMaleAge)) 
          { 
           return new ValidationResult(GetErrorMessage(person.Gender)); 
          } 
          else if (person.Gender == "F" && (person.Age < _minFemaleAge || person.Age > _maxFemaleAge)) 
          { 
           return new ValidationResult(GetErrorMessage(person.Gender)); 
          } 
    
          return ValidationResult.Success; 
         } 
    
         private string GetErrorMessage(string gender) 
         { 
          if (gender == "M") 
          { 
           return string.Format(_validationMessage, _minMaleAge, _maxMaleAge); 
          } 
          else 
          { 
           return string.Format(_validationMessage, _minFemaleAge, _maxFemaleAge); 
          } 
         } 
        } 
    } 
    

    あるいはIValidatableObjectインターフェースは、そのValidate方法を実施することにより、クラスレベルの検証を行うために実施することができます。詳細については、Class-Level Model Validation

    関連する問題