1

My question is similar to this one.

class WorkFlowData
{
      [Required]
      public InputData Data{ get; set; }

      public String Whatever { get; set; }
}

class GenericWorkFlowData
{
      public InputData Data{ get; set; }

      public String Whatever { get; set; }
}

class InputData
{
      public int ObjectID { get; set; }

      public string Name { get; set; }
}

I want to achieve that the property ObjectID to be required.

However, I would like to use the RequiredAttribute at class level and not property level. The validation should consider the property ObjectID of class InputData.

As you can see it above, it is not always that the ObjectID should be validated or set it as required, depending on which class InputData is being called, there should be a validation or not.

Edgar
  • 61
  • 7
  • You don't need to have required for built in type like int. This types aren't nullable. – Llazar Nov 09 '18 at 13:05
  • The classes will be used on jquery unobtrusive validation. For example, the user could be using WorkFlowData where the objectID should be defined, or the user could be using GenericWorkFlowData should not be defined. – Edgar Nov 09 '18 at 13:10
  • 1
    ObjectId is by default required. I'm not sure if the required can be used in class level. However you can create a custom attribute for your need. – Llazar Nov 09 '18 at 13:22
  • If you use validation the Jquery unobtrusive is called by the 'data-' so don't need to do much but even here if you want some sort of custumization can be donee. – Llazar Nov 09 '18 at 13:25
  • Yes, it seems like I cannot use at class level. I was just wondering if someone could have done smth similar like this before and had a hint. Thanks. – Edgar Nov 09 '18 at 13:27

1 Answers1

2

If you need programmatic validation, implement IValidatableObject.

 public class Blog : IValidatableObject
 {
     public int Id { get; set; }
     [Required]
     public string Title { get; set; }
     public string BloggerName { get; set; }
     public DateTime DateCreated { get; set; }
     public virtual ICollection<Post> Posts { get; set; }

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
     {
         if (Title == BloggerName)
         {
             yield return new ValidationResult
              ("Blog Title cannot match Blogger Name", new[] { "Title", “BloggerName” });
         }
     }
 }

Code from MSDN: https://learn.microsoft.com/en-us/ef/ef6/saving/validation