![](/img/trans.png)
[英]Does the DataTypeAttribute on a model do validation in MVC 3?
[英]Is the DataTypeAttribute validation working in MVC2?
據我所知,System.ComponentModel.DataAnnotations.DataTypeAttribute不適用於MVC v1中的模型驗證。 例如,
public class Model
{
[DataType("EmailAddress")]
public string Email {get; set;}
}
在上面的代碼中,不會在MVC v1中驗證Email屬性。 它在MVC v2中運行嗎?
[DataType("EmailAddress")]
默認不影響驗證。 這是此屬性的IsValid
方法(來自反射器):
public override bool IsValid(object value)
{
return true;
}
這是用於驗證電子郵件的自定義DataTypeAttribute的示例(取自此站點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));
}
}
與LukLed指出的一樣,DataTypeAttribute默認情況下不進行任何驗證。 但它確實會影響有關數據呈現方式的模板。
例如,如果在具有DataType(DataType.EmailAddress)
屬性的模型上調用Html.DisplayFor()
方法,則它將使用<a href="mailto:{0}">{0}</a>
格式化其值。 (至少在MVC RC2中)。
或者,您可以直接在字段上使用RegularExpression屬性,而不是創建自己的屬性,最終將檢查正則表達式匹配。
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = PaErrorMessages.InvalidEmailAddress)]
public string Email { get; set; }
從.NET 4.5開始,有EmailAddressAttribute ,它具有正確的IsValid
方法實現。 因此,如果您的目標是.NET 4.5,那么要進行驗證,請考慮使用EmailAddressAttribute
而不是自定義的。 例如,
public class Model
{
[EmailAddress(ErrorMessage = "INVALID EMAIL")]
public string Email {get; set;}
}
如果您對EmailAddressAttribute
的實現感到好奇,那么這里是反編譯(使用JetBrains dotPeek反編譯器)類的源代碼:
using System;
using System.ComponentModel.DataAnnotations.Resources;
using System.Text.RegularExpressions;
namespace System.ComponentModel.DataAnnotations
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class EmailAddressAttribute : DataTypeAttribute
{
private static Regex _regex = new Regex("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
static EmailAddressAttribute()
{
}
public EmailAddressAttribute()
: base(DataType.EmailAddress)
{
this.ErrorMessage = DataAnnotationsResources.EmailAddressAttribute_Invalid;
}
public override bool IsValid(object value)
{
if (value == null)
return true;
string input = value as string;
if (input != null)
return EmailAddressAttribute._regex.Match(input).Length > 0;
else
return false;
}
}
}
查看Scott Guthrie關於MVC 2驗證的博客文章。 這很棒。 http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.