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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With