Most efficient way to validate properties in Object

Ronald Rex 1,666 Reputation points
2023-10-11T16:01:06.3366667+00:00

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 !!!

C#
C#
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
    2023-10-11T17:47:02.6666667+00:00

    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) {
    		Console.WriteLine(result.ErrorMessage);
    	}
    }
    
    class Model {
    	[Required]
    	[StringLength(10)]
    	public string Name { get; set; }
    }
    

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

    https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=net-7.0


0 additional answers

Sort by: Most helpful