Set error message for validation of non-nullable types

I use ASP.NET core 3.1

I have:

class A {     public int A {get;set;} } 

When I send json model {"A": null} I get "error": "INVALID". But I wait "REQUIRED".

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#required-validation-on-the-server

I tried do as written above, but it doesn’t work.

options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(             _ => "The field is required."); 

How can I customize the message?

Add Comment
2 Answer(s)

as a trick, you could use the special field as string and cast it in receiver place!

Add Comment

Do you mean you cannot get the error message in controller?Here is a worked demo:

TestInt:

public class TestInt     {         public int a { get; set; }         public string b { get; set; }     } 

Controller:

[AcceptVerbs("GET")]         public ActionResult CheckA() {                         return View();         }         [AcceptVerbs("POST")]         public ActionResult CheckA(TestInt testInt)         {             if (!ModelState.IsValid) {                 StringBuilder result = new StringBuilder();                  foreach (var item in ModelState)                 {                     string key = item.Key;                     var errors = item.Value.Errors;                      foreach (var error in errors)                     {                         result.Append(key + " " + error.ErrorMessage);                     }                 }                  TempData["Errors"] = result.ToString();             }             return View();         } 

View:

<div class="row">     <div class="col-md-4">         <form method="post">             <div asp-validation-summary="ModelOnly" class="text-danger"></div>             <div class="form-group">                 <label asp-for="a" class="control-label"></label>                 <input asp-for="a" class="form-control" />                 <span asp-validation-for="a" class="text-danger"></span>             </div>             <div class="form-group">                 <label asp-for="b" class="control-label"></label>                 <input asp-for="b" class="form-control" />                 <span asp-validation-for="b" class="text-danger"></span>             </div>             <div class="form-group">                 <input type="submit" value="Test" class="btn btn-primary" />             </div>         </form>     </div> </div> 

startup.cs:

services.AddControllers()                 .AddMvcOptions(options =>                 {                     options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(                         _ => "REQUIRED");                 }); 

result: enter image description here

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.