When decorating view model properties with validation attributes, it's straightforward to then display various error messages to the user when an input is invalid. For example, the following blocks of code generate the error screenshotted below:
[Required]
[EmailAddress]
public string Email { get; set; }
<span asp-validation-for="Input.Email" ></span>
I am trying to implement my own validation rules by implementing the IValidatableObject interface, because the min and max values I want to check against are only known at runtime - this means it's not possible to pass values to the Range
attribute as follows:
[Range(<some-unknown-value>, <another-unknown-value>)]
public double MyValue { get; set; }
The documentation below suggests that IValidatableObject should be able to achieve similar results to the above, but other documentation on IValidatableObject suggests that this approach to validation is more intended for REST calls than to be integrated with .NET Core's MVC design pattern. Has anyone managed to get the design pattern as documented below to work?
CodePudding user response:
ModelState errors are implicitly injected into the view to populate instances of <span asp-validation-for="<variable-name>"></span>
, so controllers need to return the form-containing view again to reflect the validation errors from IValidatableObject.