0

I have a class "SampleDTO.cs" and i would like assign data annanatoation attributes during run time.

For an example

SampleDTO.cs {

public string Name
{
    get;set;

}

}

I need to force, required field validation, minimum or maximum field validation based on condition. I have been searching for a forum and couldnt get any solution..

My expection is,

if(some condition1)
{
    check SampleDTO.Name property for Required field validator check.
}
else if(some condition2)
{
    check SampleDTO.Name property for minimum and maximum length check.
}
else{
    someother check.
}

(This can be done easily, by decorating the required, min/max length attribute on the SampleDTO.cs class. I am expecting this to implement it dynamically instead of static assignment.)

Thanks in advance.

kamal
  • 9
  • 4
  • Is the condition linked to the DTO itself, or is it external to the DTO? Put another way, can you give an example condition? – Kirk Larkin Sep 05 '17 at 20:01
  • Seems like there is a better way to go about what you want, but this may be possible, depending on exactly what you need, by customizing DataAnnotationsModelValidatorProvider. See: https://stackoverflow.com/questions/4088274/possible-to-change-data-annotations-during-runtime-asp-net-mvcs-range-requ – stephen.vakil Sep 05 '17 at 20:13

1 Answers1

-1

Could you not do a string.IsNullorWhitespace(SampleDTO.Name) for required? and then check the length for your min and max in your conditionals?

If you mean dynamically as in not setting properties, these string methods would work.

  • yes, it will work, but we have to write our own custom methods for each condition for string length, null, etc., This is not for one class and this scope will be bigger. So i am looking to use the data annotation instead of writting our own code. :) Thank you very much for your quick reply. – kamal Sep 05 '17 at 20:36
  • I see. I think I misunderstood the question at first. You could do what steven.vakil suggested above, but I would write some javascript for it, good luck! – Brian Elliott Sep 06 '17 at 21:22
  • utilizing the data annotation on our custom class is possible, i did it successfully. Example, in my class i have created a property and wrote thefollowing definition. RequiredAttribute oRequired = new RequiredAttribute { AllowEmptyStrings = false, ErrorMessage = message }; if (oRequired.IsValid(this.UtteranceVal)) { return false; } – kamal Sep 13 '17 at 13:42