0

What I'm trying to do seems really simple but I'm struggling with it since this morning...

I just want to force French language for html.ValidationMessageFor(x=>x.Name)

Here my name property :

[Required]
public string Name { get; set; }

Right now, if I try to validate a form without filling the property I've got the "The Name field is required."

  1. Where does this message "The {0} is required." come from ?

  2. How can I change the language of it without having to override all my [Required] properties in all my ViewModels with something like :

[Required(ErrorMessageResourceName ="Required",ErrorMessageResourceType =typeof(FrenchDataAnnotation))]

Thanks a lot.

LazZiya
  • 5,286
  • 2
  • 24
  • 37
El MoZo
  • 157
  • 1
  • 10
  • 1
    Could you please have a look on [`this thread`](https://stackoverflow.com/questions/50888963/localize-required-annotation-in-french-implicitly)? Are you looking for this? – Md Farid Uddin Kiron Nov 21 '22 at 07:27
  • As Alexandre Jobin pointed in OP answer, this does work only for Model binding errors, not for DataAnnotation like Required and StringLength. – El MoZo Nov 21 '22 at 09:38

1 Answers1

0

You can create a custom validation attribute that implements the default Required attribute and use it for validation:

public sealed class ExRequiredAttribute : RequiredAttribute
{
    public ExRequiredAttribute() : base()
    {
        this.ErrorMessage = "my custom error message...!"
    }
}

Then use it like:

[ExRequired]
public string Name { get; set; }

Another solution is to use third party localization nuget like XLocalizer which overrides all default data annotations, ModelBinding and IdentityErrors.

LazZiya
  • 5,286
  • 2
  • 24
  • 37