Search code examples
c#asp.net-coredata-annotationsasp.net-core-3.1modelstate

How we can fetch validation rule from ModelState


Is there anyway to fetch the validation rule from ModelState dictionary. For example

I have following data annotation attribute in my model

[StringLength(64, MinimumLength = 8, ErrorMessage = "{0} must be between {2} to {1} characters")]
public string Password { get; set; }

So while validating Modelstate can we get MinimumLength and MaximumLenght?

I want to send both of these values in response so front-end can generate localize message using these values.

my sample response is as follow

{
  "errorCode" : 1234,
  "message": : "Password must be between 8 to 64 characters",
  "args" : ["8","64"]
}

So using this error code front end can generate localize message using args.


Solution

  • It's difficult to make this even if we add ConfigureApiBehaviorOptions the object doesn't contains validation rules i would suggest the easiest way is to make a json object inside your string , and like this you can use directly in the format that you want

     [StringLength(64, MinimumLength = 8, ErrorMessage = "{{error:'{0} must be between {2} to {1} characters ',args:'[{1},{2}]' }}") ]