Wednesday 13 February 2019

DotnetCore Web API model validation message from resource file.

It's so simple you just need to add resource file ValidationMessage.resx under the project as I have added. After adding it you will found that corresponding ValidationMessage.Designer.resx is not available inside resource folder.


So you need to set Custom Tool property for the .resx file as ResXFileCodeGenerator, as soon as we add it, will find ValidationMessage.Designer.resx.


After enabling it and writing appropriate model with validation attribute with ErrorMessageResourceName = "Password", ErrorMessageResourceType = typeof(ValidationMessage) you may found your required 
ModelValidationState Error message from your resource file.


using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using CoreApp.WebApi.Resources;
 
namespace CoreApp.WebApi.Models
{
    public class UserLogin
    {
        [DisplayName("LoginId")]
        public int UserId { getset; }
 
        [Required(ErrorMessageResourceName = "Password", ErrorMessageResourceType = typeof(ValidationMessage)), MinLength(4), MaxLength(10)]
        public string Password { getset; }
        public DateTime? RequestTime { getset; }
 
    }
}



Note:
Personally I fall in a situation in which I was using services.AddMvcCore() and with this model validation with  DataAnnotations was not working. So after searching out found that we need to use
services.AddDataAnnotations() Extensions in order to enable DataAnnotaions validation. And that worked for DotNetCore Web API model validations.

services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonFormatters()
.AddDataAnnotations()
.AddXmlSerializerFormatters();