I'm trying to build a custom message validation that involves two or more attribute.
Here is a simplified version of my DTO:
public class FooDTO
{
public int Id { get; set; }
public int Name { get; set; }
//more attributes...
public bool IsValid
{
get
{
if (string.IsNullOrEmpty(this.Name) && (this.Id == 0))
return false; //You will have to specify at least one of the following: Id or Name
if (this.Name == "Boo" && this.ID = 999)
return false; //Boo name and Id of 99 are forbidden
//More validation ifs.
return true;
}
}
}
And my current controller implementation looks like this:
public async Task<IActionResult> DoSomething(FooDTO fooDTO)
{
if (!FooDTO.IsValid)
return BadRequest("");
// Rest of code
}
This implementation does not acknowledge the user with the correspond message, like when both the Id
and Name
are missing, I want the user to be notified with something like "You will have to specify at least one of the following: Id or Name" validation error.
Is there a way to use ValidationAttribute
to achieve validation for two of more properties that involves complex validation? (this is my preferred solution)
Or an elegant way to build the custom error message to be sent over in the BadRequest(string message)
overload?
Use can use IValidatableObject
to implement custom validation:
public class FooDTO : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
//more attributes...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Name) && (Id == 0))
yield return new ValidationResult("You will have to specify at least one of the following: Id or Name", new[] { "Id", "Name" });
if (Name == "Boo" && Id == 999)
yield return new ValidationResult("Boo name and Id of 99 are forbidden", new[] { "Id", "Name" });
}
}
and in controller:
public async Task<IActionResult> DoSomething(FooDTO fooDTO)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
// Rest of code
}
For more information read Model validation in ASP.NET Core MVC and Razor Pages