Multi Language error messages using Data Annotation
- Data Annotations attributes are used for validation.
- The error messages are shown to user, if validation fails. We can also show the error messages in multiple languages.
- In this article we will see how to implement multi language error messages with Data Annotations.
Watch Video
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using MultiExample.MultiResources;
using System.Web.Mvc;
namespace MultiExample.Models
{
public class Register
{
[Required(ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "FirstName_Required")]
public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Age_Required")]
[Range(20, 40, ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Age_Range")]
public int Age { get; set; }
[Required(ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Email_Required")]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Email_Format")]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Password_Required")]
[DataType(DataType.Password)]
[StringLength(10, ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "Password_Length")]
public string Password { get; set; }
[Required(ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "ConfirmPassword_Required")]
[DataType(DataType.Password)]
[StringLength(10, ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "ConfirmPassword_Range")]
[Compare("Password", ErrorMessageResourceType = typeof(Multi), ErrorMessageResourceName = "ConfirmPassword_Compare")]
public string ConfirmPassword { get; set; }
}
}
Above is our Model. We have used Data Annotation attributes for validation. We have used two properties i.e. ErrorMessageResourceType and ErrorMessageResourceName.
ErrorMessageResourceType : This property accepts the type of resource from which we want to pick the error message. In the above Model we have used Multi, which is the resx file.
ErrorMessageResourceName : This property accepts name of the key in the resx file which holds the text for error message.
Using these two proeprties we can pick error messages from resource files and can show to user depending upon language selected.
Screenshot :
English
Spanish
French
0 comments:
Post a Comment