Class-level validation

女生的网名这么多〃 提交于 2019-11-28 08:57:36

问题


I am validating a class with DataAnnotations utils.

I have a class that has a Title property and an Item property. I want to apply a RequiredAttribute to the Title property but it should be invalid only if the Item property is null; if the Item property is set with an object, the Title is not required.

In short words, I want the RequiredAttribute to validate only if a condition in the class is satisfied.

How can this be done.

Update

As I didn't find other way, and since I usually don't need this functionality so often, I decided to make it the rough way using a class-level validator. my question is then, is there a way to manually update the UI to make that Title TextBox with a red frame, i.e. to invalidate it?

Update 2
I want the class-level validator to summarize on a field. For example, I have to fields Cost and SalesPrice, I wanna make sure that SalesPrice > Cost and invalidate the SalesPrice otherwise, I don't want a global validation error on the class level.

I prefer to do it the xamly way.


回答1:


You may be able to do this by creating a custom validation attribute for the class. Unfortunately DataAnnotation attributes assigned to properties cannot access other properties of the parent class as far as I am aware hence the need to create a class validator.
Using the System.ComponentModel.DataAnnotations namespace you will need to create you custom attribute class inheriting from ValidationAttribute and override the IsValid method (I have not tested the code below but it should get you going):

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
sealed public class CustomAttribute: ValidationAttribute
{
  public CustomAttribute()
  {
  }

  public override bool IsValid(object value)
  {
     if(value is myClass)
     {
       return ((myClass)value).Item != null &&
         string.IsNullOrEmpty(((myClass)value).Title) ? false : true;
     }
     else return true;
  }
}

Digging a little further it appears that whilst cross field validation it not possible out of the box it can be achieved by extending the framework to support it. See this article for details, hopefully this will be added to future versions of MVC.




回答2:


well, on property level contingent validations are hard to achieve in MVC. but u can extend the framework or u can use some other library to achieve the goal. i m using foolproof validation by nick successfully for contingent validations in my project. u can take a look at it here



来源:https://stackoverflow.com/questions/3880727/class-level-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!