开发者

Class-level validation

开发者 https://www.devze.com 2023-01-18 21:49 出处:网络
I am validating a class with DataAnnotations utils. I have a class that has a Title property and an Item property.

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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消