Is the DataTypeAttribute validation working in MVC2?

后端 未结 5 1453
鱼传尺愫
鱼传尺愫 2020-12-03 07:26

As far as I know the System.ComponentModel.DataAnnotations.DataTypeAttribute not works in model validation in MVC v1. For example,

public class Model
{
  [Da         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 07:50

    [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;
    }
    

    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));
        }
    }
    

提交回复
热议问题