Create Custom DataTypeAttribute for Validation and Custom Display in ASP.NET MVC 2.0

I have been blogging about ASP.NET MVC 2.0 Preview 1 since it has been released. You can catch up with my series of posts via these links:

The code in these examples is based on the code samples I am writing for the next Tampa ASP.NET MVC Developer Group Meeting and I will make it available for download after the meeting.

 

DataTypeAttribute with Template Helpers in ASP.NET MVC 2.0

In the last post, DataTypeAttribute and ASP.NET MVC 2.0 Goodness with Templated Helpers, I showed how we can take advantage of theDataTypeAttribute in System.ComponentModel.DataAnnotations with the new template helpers in ASP.NET MVC 2.0 ( Html.DisplayFor, Html.LabelFor, and Html.EditFor ) to have the ASP.NET MVC Framework render the Email Property as a Mailto Hyperlink in your view. Here is the Contact Entity's Buddy Class with the Email Property decorated with [DataType(DataType.EmailAddress)] below:

 

internal class Contact_Metadata

{

    [Required(ErrorMessage = "Name is required.")]

    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]

    public string Name { get; set; }

 

    [Required(ErrorMessage = "Email is required.")]

    [StringLength(200, ErrorMessage = "Email must be 200 characters or less.")]

    [RegularExpression(@"/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*",ErrorMessage = "Valid Email Address is required.")]

    [DataType(DataType.EmailAddress)]

    public string Email { get; set; }

}

 

One of the things that bothers me initially about the Email Property is that we have two attributes that have to do with the fact that this property represents a valid email address:

 

[RegularExpression(@"/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*",ErrorMessage = "Valid Email Address is required.")]

[DataType(DataType.EmailAddress)]

 

Wouldn't it be nice if we could just combine these two attributes into a single attribute that does both since they go hand-in-hand? I think so :)

Now there are several ways to do this, but since the DataTypeAttribute inherits from ValidationAttribute, let's go ahead and make a custom DataTypeAttribute that will handle our custom display and validation needs.

 

Custom DataTypeAttribute for ASP.NET MVC 2.0 Template Helpers

Keep in mind we are just playing here and there are several ways to pull this off, but I am going to create an EmailAddressAttribute that inherits from DataTypeAttribute and overrides the IsValid Method that does validation. I have coded it quickly as follows:

 

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

    }

}

 

We now have 1 attribute that will handle the cool output display as well as the validation so we can remove the two attributes from before:

 

 

[RegularExpression(@"/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*",ErrorMessage = "Valid Email Address is required.")]

[DataType(DataType.EmailAddress)]

 

and replace it with this:

 

[EmailAddress(ErrorMessage = "Valid Email Address is required.")]

 

making the new Contact Entity Buddy Class look like the following:

 

internal class Contact_Metadata

{

    [Required(ErrorMessage = "Name is required.")]

    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]

    public string Name { get; set; }

 

    [Required(ErrorMessage = "Email is required.")]

    [StringLength(200, ErrorMessage = "Email must be 200 characters or less.")]

    [EmailAddress(ErrorMessage = "Valid Email Address is required.")]

    public string Email { get; set; }

}

 

This feels better. I kinda like it, but we should probably talk about other ways to pull off this type of functionality in future posts as well as start talking about some of the other cool things in ASP.NET MVC 2.0 Preview 1 before I beat this dead horse too much longer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值