Home:ALL Converter>C# add validation on a setter method

C# add validation on a setter method

Ask Time:2011-05-25T23:52:04         Author:Marthin

Json Formatter

I have a a couple of variables that i define in C# by:

public String firstName { get; set; }
public String lastName { get; set; }
public String organization { get; set; }

What i want is to add validation to these methods when you try to set a value. Lets say your going to set a value for firstName, the i should pass thrue a regexp to actuelly be set, otherwise an exception should be thrown. Is this possible to build with this "short syntax" or should I go for standard (like in JAVA) getters and setters and in there validate the data?

Author:Marthin,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/6127290/c-sharp-add-validation-on-a-setter-method
jason :

If you want to validate when the property is set, you need to use non-auto properties (i.e., manually defined get and set methods).\n\nBut another way to validate is to have the validation logic separate from the domain object.\n\nclass Customer {\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public string Organization { get; set; }\n}\n\ninterface IValidator<T> {\n bool Validate(T t);\n}\n\nclass CustomerValidator : IValidator<Customer> {\n public bool Validate(Customer t) {\n // validation logic\n }\n}\n\n\nThen, you could say:\n\nCustomer customer = // populate customer\nvar validator = new CustomerValidator();\nif(!validator.Validate(customer)) {\n // head splode\n}\n\n\nThis is the approach I prefer:\n\n\nA Customer should not responsible for validating its own data, that is another responsibility and therefore should live elsewhere.\nDifferent situations call for different validation logic for the same domain object.\n",
2011-05-25T15:55:56
StriplingWarrior :

What you have now are called \"auto-properties,\" and only perform a simple \"get/set\". In order to customize the behavior of the get or set, you will need to convert the properties to field-backed properties:\n\nprivate string _firstName;\npublic string FirstName \n{ \n get {return _firstName;} \n set \n {\n Validate(value); _firstName = value;\n }\n}\n\n\nNote that I changed String to string and capitalized the property name, in following accepted C# naming best practices.",
2011-05-25T15:54:00
Prisoner ZERO :

I wouldn't add validation in the setter at all. Rather, I would create a function called validate instead...that way all your validation code is in one spot rather scattered throughout your setters.",
2011-05-25T15:55:38
M.Hassan :

It's best practice to apply SRP. Set the validation in a separate class.\n\nYou can use FluentValidation\n\n Install-Package FluentValidation\n\n\nYou would define a set of validation rules for Customer class by inheriting from AbstractValidator<Customer>:\n\nExample:\n\n public class CustomerValidator : AbstractValidator<Customer> {\n public CustomerValidator() {\n RuleFor(x => x.Surname).NotEmpty();\n RuleFor(x => x.Forename).NotEmpty().WithMessage(\"Please specify a first name\");\n RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);\n RuleFor(x => x.Address).Length(20, 250);\n RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage(\"Please specify a valid postcode\");\n }\n\n private bool BeAValidPostcode(string postcode) {\n // custom postcode validating logic goes here\n }\n }\n\n\nTo run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.\n\n Customer customer = new Customer();\n CustomerValidator validator = new CustomerValidator();\n\n ValidationResult result = validator.Validate(customer);\n\n if(! results.IsValid) {\n foreach(var failure in results.Errors) {\n Console.WriteLine(\"Property \" + failure.PropertyName + \" failed validation. Error was: \" + failure.ErrorMessage);\n\n\n}\n}",
2019-08-19T20:52:20
yy