I had a requirement to set a regex expression dynamically, instead of creating my own validators as @Golda suggested in the comments, I cheated and just set the data-val errors using properties on my model, this is all the required attribute does anywhere with the help of a TagHelper.
Build your model as usual and add an additional property to hold the error message
[Required(ErrorMessage = "static error message")] // Leave this here for server side
public string AttributeValue { get; set; }
public string AttributeValueRequiredErrorMessage { get; set; }
In the controller make sure you set this property
public async Task<IActionResult> SomeAction()
{
.... // other logic
var attributeValueRequiredErrorMessage = callTheDb();
var model = new Model()
{
AttributeValueRequiredErrorMessage = attributeValueRequiredErrorMessage
}
return View(model);
}
Then in your view simply do this
<input asp-for="AttributeValue " data-val-required="@Model.AttributeValueRequiredErrorMessage " />
This would work for a quick win but I would probably look at an alternative if you were doing this in multiple places.
If you dont mind taking the hit server side, you could also implement the [Remote] attribute if you're in dotnet core, see docs: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.0#remote-attribute