Home > database >  How do you Integrate IValidatableObject with Razor Syntax
How do you Integrate IValidatableObject with Razor Syntax

Time:07-25

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>

enter image description here

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?

https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/custom-validation-with-ivalidatableobject-in-mvc/

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.

  • Related