是DataTypeAttribute验证在MVC2工作吗? [英] Is the DataTypeAttribute validation working in MVC2?
问题描述
据我所知System.ComponentModel.DataAnnotations.DataTypeAttribute在MVC V1模型验证不工作。例如,
As far as I know the System.ComponentModel.DataAnnotations.DataTypeAttribute not works in model validation in MVC v1. For example,
public class Model
{
[DataType("EmailAddress")]
public string Email {get; set;}
}
在上面的codeS,电子邮件属性将不会在MVC V1验证。难道是MVC V2工作?
In the codes above, the Email property will not be validated in MVC v1. Is it working in MVC v2?
推荐答案
[数据类型(EmailAddress的)]
默认不影响验证。这是的IsValid
此属性(由反射镜)的方法:
[DataType("EmailAddress")]
doesn't influence validation by default. This is IsValid
method of this attribute (from reflector):
public override bool IsValid(object value)
{
return true;
}
这是示例自定义DataTypeAttribute来验证电子邮件(从本网站<一所href=\"http://davidhayden.com/blog/dave/archive/2009/08/12/CustomDataTypeAttributeValidationCustomDisplay.aspx\" rel=\"nofollow\">http://davidhayden.com/blog/dave/archive/2009/08/12/CustomDataTypeAttributeValidationCustomDisplay.aspx):
This is example of custom DataTypeAttribute to validate Emails (taken from this site http://davidhayden.com/blog/dave/archive/2009/08/12/CustomDataTypeAttributeValidationCustomDisplay.aspx):
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class EmailAddressAttribute : DataTypeAttribute
{
private readonly Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled);
public EmailAddressAttribute() : base(DataType.EmailAddress)
{
}
public override bool IsValid(object value)
{
string str = Convert.ToString(value, CultureInfo.CurrentCulture);
if (string.IsNullOrEmpty(str))
return true;
Match match = regex.Match(str);
return ((match.Success && (match.Index == 0)) && (match.Length == str.Length));
}
}
这篇关于是DataTypeAttribute验证在MVC2工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!