本文介绍了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 中是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 18:29