Original: MVC validation 06-Custom Error message
This article experiences custom error messages.
System default error message
In MVC validation 02-Custom validation rules, message validation, we've customized a class that validates email. If the input message format is wrong, the system default error message appears.
Effect:
To modify the error message by errormessage
"email format error")]
"Mail")]
Public string Email {get; set;}
Effect:
Overriding the Formaterrormessage method in a custom validation attribute
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using SYSTEM.WEB.MVC;
namespace Mvcvalidation.extension
{
Public Sealed class Emailattribute:validationattribute, iclientvalidatable
{
Public Const string @ "^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$ ";
Public Emailattribute ()
{
}
overriding base class methods
Public Override BOOL IsValid (objectvalue)
{
if (valuenull)
return true;
if (valueisstring)
{
New Regex (REG);
return regex.ismatch (value. ToString ());
}
return false;
}
Public System.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context)
{
New Modelclientvalidationrule
{
"Email",
ErrorMessage = formaterrormessage (metadata. GetDisplayName ())
};
yield return rule;
}
<summary>
Formatting error messages
</summary>
<param name= "Name" > property name </param>
<returns></returns>
Public Override string Formaterrormessage (string name)
{
return This string. Format ("{0} attribute did not enter the correct email", name);
}
}
}
Effect: