I develop ASP.NET MVC4 app, EF Code first. I have base class:
public class Entity
{
public int Id { get; set; }
public string Title { get; set; }
}
And i have some derived classes, for example:
public class City : Entity
{
public int Population { get; set; }
}
And many other derived classes (Article, Topic, Car etc). Now i want to implement "Required" attribute to Title property in all classes and i want there are different ErrorMessages for different derived classes. For example, "Title must not be empty" for Topic class, "Please name your car" for Car class etc. How can i do this? Thanks!
You could make the property virtual in the base class:
public class Entity
{
public int Id { get; set; }
public virtual string Title { get; set; }
}
and then override it in the child class, make it required and specify the error message that you would like to be displayed:
public class City : Entity
{
public int Population { get; set; }
[Required(ErrorMessage = "Please name your city")]
public override string Title
{
get { return base.Title; }
set { base.Title = value; }
}
}
Alternatively you could use FluentValidation.NET
instead of data annotations to define your validation logic and in this case you could have different validators for the different concrete types. For example:
public class CityValidator: AbstractValidator<City>
{
public CityValidator()
{
this
.RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Please name your city");
}
}
public class CarValidator: AbstractValidator<Car>
{
public CityValidator()
{
this
.RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("You should specify a name for your car");
}
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With