6

I am creating asp.net mvc application in which I storing my error messages in my database, now I want to use required field annotation instead of custom js validations when user clicks submit, my models looks like below,

[Required(ErrorMessage = "static error message")]
public string AttributeValue { get; set; }

I want to add dynamic error message instead of -> (static error message)

is there a way to add dynamic error message from controller.

7
  • For best performance do not hit the database every time you need to read a single text. Better build your own Resource file for dyanamic error message. Commented May 14, 2019 at 9:41
  • @MannanBahelim the field name can be changed by user Commented May 14, 2019 at 9:44
  • its like question and answer Commented May 14, 2019 at 9:44
  • On validation failed you can add ModelState.AddModelError("AttributeValue", "error message"); to controller Commented May 14, 2019 at 9:49
  • @MannanBahelim yes I know that but I want to add error message during HTTPGet and not post Commented May 14, 2019 at 9:50

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.