Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# add validation on a setter method

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?

like image 553
Marthin Avatar asked May 25 '11 15:05

Marthin


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


3 Answers

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).

But another way to validate is to have the validation logic separate from the domain object.

class Customer {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Organization { get; set; }
}

interface IValidator<T> {
    bool Validate(T t);
}

class CustomerValidator : IValidator<Customer> {
    public bool Validate(Customer t) {
        // validation logic
    }
}

Then, you could say:

Customer customer = // populate customer
var validator = new CustomerValidator();
if(!validator.Validate(customer)) {
    // head splode
}

This is the approach I prefer:

  1. A Customer should not responsible for validating its own data, that is another responsibility and therefore should live elsewhere.
  2. Different situations call for different validation logic for the same domain object.
like image 136
jason Avatar answered Sep 22 '22 02:09

jason


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:

private string _firstName;
public string FirstName 
{ 
    get {return _firstName;} 
    set 
    {
       Validate(value); _firstName = value;
    }
}

Note that I changed String to string and capitalized the property name, in following accepted C# naming best practices.

like image 43
StriplingWarrior Avatar answered Sep 23 '22 02:09

StriplingWarrior


It's best practice to apply SRP. Set the validation in a separate class.

You can use FluentValidation

       Install-Package FluentValidation

You would define a set of validation rules for Customer class by inheriting from AbstractValidator<Customer>:

Example:

  public class CustomerValidator : AbstractValidator<Customer> {
    public CustomerValidator() {
      RuleFor(x => x.Surname).NotEmpty();
      RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
      RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
      RuleFor(x => x.Address).Length(20, 250);
      RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
    }

    private bool BeAValidPostcode(string postcode) {
      // custom postcode validating logic goes here
    }
  }

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.

   Customer customer = new Customer();
   CustomerValidator validator = new CustomerValidator();

   ValidationResult result = validator.Validate(customer);

 if(! results.IsValid) {
   foreach(var failure in results.Errors) {
       Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);

} }

like image 36
M.Hassan Avatar answered Sep 21 '22 02:09

M.Hassan