您的位置:首页 > 其它

MVC验证06-自定义错误信息

2014-06-28 00:18 323 查看
原文:MVC验证06-自定义错误信息本文体验自定义错误信息。

  系统默认的错误信息

在"MVC验证02-自定义验证规则、邮件验证"中,我们自定义了一个验证Email的类。如果输入邮件格式错误,出现系统默认的报错信息。

效果:


             

 

  通过ErrorMessage来修改错误信息

[Email(ErrorMessage = "Email格式错误")]


[code][Display(Name = "邮件")]


public string Email { get; set; }

[/code]

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

效果:





  在自定义验证特性中重写FormatErrorMessage方法

using System.ComponentModel.DataAnnotations;


[code]using System.Text.RegularExpressions;


using System.Web.Mvc;


 


namespace MvcValidation.Extension


{


public sealed class EmailAttribute : ValidationAttribute, IClientValidatable


{


public const string reg = @"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$";


 


public EmailAttribute()


    {  


}


 


//重写基类方法


public override bool IsValid(object value)


    {


if (value == null)


return true;


 


if (value is string)


{


Regex regEx = new Regex(reg);


return regEx.IsMatch(value.ToString());


}


return false;


}


 


public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)


    {


ModelClientValidationRule rule = new ModelClientValidationRule


{


ValidationType = "email",


ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())


};


yield return rule;


}


 


/// <summary>


/// 格式化错误信息


/// </summary>


/// <param name="name">属性名</param>


/// <returns></returns>


public override string FormatErrorMessage(string name)


    {


return  this.ErrorMessage ?? string.Format("{0}属性没有输入正确的Email", name);


}


}


}


 

[/code]

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

效果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: