Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

.net - Class-level validation

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...