Most efficient way to validate properties in Object

Ronald Rex 1,666 Reputation points

Hi Friends. I have an object that is used to make a request to a web service. It has basic properties such as name, address, password etc. However, these properties might have certain restrictions on them as far as length of the string value and it must have valid characters, basically each property needs to be validated before I send the request object. I was wondering what is the most efficient way to validate the object. Thanks !!!

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,408 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,406 Reputation points

    You could annotate your request class & use Validator.TryValidateObjects to get the validation errors (if any):

    using System.ComponentModel.DataAnnotations;
    Model m = new Model {
    	Name = "12345678910"
    ICollection<ValidationResult> results = new List<ValidationResult>();
    if (!Validator.TryValidateObject(m, new ValidationContext(m), results, validateAllProperties: true)) {
    	foreach (ValidationResult result in results) {
    class Model {
    	public string Name { get; set; }

    Here's the list of available data annotations you can use:

0 additional answers

Sort by: Most helpful