I am using data annotations in C# to validate a POCO class. I would like to be able to specify different validation schemes in different situations. Eg minimum validation for trusted data sources, but a higher level of validation for data collected via a website form open to the public.
I've Googled and i'm not sure if: A) I'm not using the right terms, or B) this is the wrong approach entirely which is why i'm not finding anything. It seems like this might be a common need.
To illustrate what i'd like to do:
public class TestClass {
[Required]
[EmailAddress]
[WhitelistCharactersOnly(ValidationScheme = ValidationSchemes.Untrusted)]
public string EmailAddress { get; set; }
}
I understand that I could do something with custom attributes but i'd like to avoid reinventing the wheel if possible.
So as not to solicit too much debate, my question is this: Is there a way to achieve what I want to do that is part of the C# framework at present?
If you're using the MVC framework for validation you can take advantage of the MetadataTypeAttribute
.
[MetadataType(typeof(ICustomerValidation1))]
public class CustomerValidation1 : CustomerBase { }
public class CustomerBase
{
public string Title { get; set; }
}
public interface ICustomerValidation1
{
// Apply RequiredAttribute
[Required(ErrorMessage = "Title is required.")]
string Title { get; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.