Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Validation ErrorMessage changed on language base

I have to set validation messages based on language. As you can see bellow I have this for english.

        [Required(ErrorMessage = "Email field is required")]  
        [StringLength(254, MinimumLength = 7, ErrorMessage="Email should be between 7 and 254 characters")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage= "Please insert a correct email address")]
        public string Email { get; set; }

I've looked how can I implement localization for error messages, but all I found is how to do this with resource files. I need to do the localization based on what data I've got form CMS(Sitecore) database.

To map the Sitecore data to C# models I use Glass Mapper.

How this can be implemented?

like image 834
Radu Avatar asked Jan 26 '26 08:01

Radu


1 Answers

You can you sitecore dictionary for the messages and you need to implement a new class in this way

 using Sitecore.Globalization;
 using System.ComponentModel.DataAnnotations;
 using System.Runtime.CompilerServices;

 public class CustomRequiredAttribute : RequiredAttribute
{
    /// <summary>
    /// The _property name
    /// </summary>
    private string propertyName;

    /// <summary>
    /// Initializes a new instance of the <see cref="CustomRequiredAttribute"/> class.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    public CustomRequiredAttribute([CallerMemberName] string propertyName = null)
    {
        this.propertyName = propertyName;
    }

    /// <summary>
    /// Gets the name of the property.
    /// </summary>
    /// <value>
    /// The name of the property.
    /// </value>
    public string PropertyName
    {
        get { return this.propertyName; }
    }

    /// <summary>
    /// Applies formatting to an error message, based on the data field where the error occurred.
    /// </summary>
    /// <param name="name">The name to include in the formatted message.</param>
    /// <returns>
    /// An instance of the formatted error message.
    /// </returns>
    public override string FormatErrorMessage(string name)
    {
        return string.Format(this.GetErrorMessage(), name);
    }

    /// <summary>
    /// Gets the error message.
    /// </summary>
    /// <returns>Error message</returns>
    private string GetErrorMessage()
    {
        return Translate.Text(this.ErrorMessage);
    }
}

and the model for the form will look like :

 public class AddressViewModel
 {
   [CustomRequiredAttribute(ErrorMessage = "Shipping_FirstName_Required")]
    public string FirstName { get; set; }
 }
like image 199
Vlad Iobagiu Avatar answered Jan 27 '26 22:01

Vlad Iobagiu