Class Level Validation

I am checking a class with DataAnnotationsutils.

I have a class that has a property Titleand a property Item. I want to apply RequiredAttributeto a property Title, but it should be invalid only if the property Itemis null; if a property Itemis specified with an object, Titlenot required.

In short, I want to RequiredAttributecheck only if the condition in the class is satisfied.

How can I do that.

Update

Since I did not find another way, and since I usually do not need such a function so often, I decided to do it rudely using the class level validator. my question is is there a way to manually update the user interface to make this TextBox with a red frame, i.e. make it invalid?

Update 2
I want the class level validator to summarize in a field. For example, I have fields Cost and SalesPrice, I want to make sure that SalesPrice> Cost and invalidity of SalesPrice otherwise, I do not want a global class-level validation error.

I prefer to do it differently.

+3
source share
2 answers

, . , DataAnnotation, , , , , .
System.ComponentModel.DataAnnotations, , ValidationAttribute, IsValid ( , ):

[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;
  }
}

, , , , . . , , MVC.

+6

, MVC . u , - . . u

0

Source: https://habr.com/ru/post/1768397/


All Articles