Model Validation Extension code failed
Hi everyone
I wanted to create a static base method instead of writing a Validate Method separately for each model, but it didn't happen.
Is there a way? or is it necessary to try another method?
Controller
[HttpPost]
public IActionResult SaveMember(MemberPostModel postedMember)
{
if (postedMember.Validate()) return null;
// other code ...
}
Model
public class MemberPostModel : PostModelBase<MemberPostModel>, IDto
{
public int Id { get; set; }
// other properties...
}
Base Model for Validation
public static class PostModelBase<TPostModel> where TPostModel : IDto
{
public static bool Validate(this TPostModel postModel)
{
foreach (var prop in postModel.GetType().GetProperties())
{
if (prop.PropertyType == typeof(string))
{
var length = prop.GetValue(postModel)?.ToString().Length.ToInt32();
var attr = prop.GetPropertyCustomAttribute<StringLengthAttribute>();
if (attr == null) continue;
if (attr.MaximumLength == length) continue;
else return false;
}
}
return true;
}
}
CodePudding user response:
Why does it have to be static at all? This looks like it should work if you simply remove the static keyword. The static keyword on classes in C# doesn't do anything, except for preventing you from creating non-static methods. In my opinion it makes sense to have separate validators for your models. What if you need to check some additional property in the future?
CodePudding user response:
You cannot inherit a static class because they are sealed and abstract. If you need to inherit a class, you'll need to make it non static.