DataTypeAttribute验证是否在MVC2中工作? [英] Is the DataTypeAttribute validation working in MVC2?

查看:170
本文介绍了DataTypeAttribute验证是否在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;}
}

在上述代码中,电子邮件属性将不会在MVC v1。是否在MVC v2中工作?

In the codes above, the Email property will not be validated in MVC v1. Is it working in MVC v2?

推荐答案

[DataType(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验证电子邮件的示例(取自本网站 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆