首页 新闻 赞助 找找看

如何自定义验证属性

0
悬赏园豆:20 [已关闭问题] 关闭于 2014-04-25 14:21

这几天在捣鼓自定义验证属性,网上搜罗很多都是在MVC中使用的。

我要的效果是后台属性添加上自定义属性标签,然后业务处理中用到这个属性时会触发自定义属性的验证。

自定属性代码写好了,可测试中就是不触发这个自定义属性的方法。请了解的大侠帮帮忙。

自定义验证属性代码如下:

[AttributeUsage(AttributeTargets.Property |
  AttributeTargets.Field, AllowMultiple = false)]
public sealed class CustomAttribute : ValidationAttribute
{
 // Internal field to hold the mask value.
    readonly string _mask;

    public string Mask
    {
        get { return _mask; }
    }

    public CustomAttribute(string mask)
    {
        _mask = mask;
    }


    public override bool IsValid(object value)
    {
        var phoneNumber = (String)value;
        bool result = true;
        if (this.Mask != null)
        {
            result = MatchesMask(this.Mask, phoneNumber);
        }
        return result;
    }

    // Checks if the entered phone number matches the mask.
    internal bool MatchesMask(string mask, string phoneNumber)
    {
        if (mask.Length != phoneNumber.Trim().Length)
        {
            // Length mismatch.
            return false;
        }
        for (int i = 0; i < mask.Length; i++)
        {
            if (mask[i] == 'd' && char.IsDigit(phoneNumber[i]) == false)
            {
                // Digit expected at this position.
                return false;
            }
            if (mask[i] == '-' && phoneNumber[i] != '-')
            {
                // Spacing character expected at this position.
                return false;
            }
        }
        return true;
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentCulture,
          ErrorMessageString, name, this.Mask);
    }
}
View Code

实体类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Customer 的摘要说明
/// </summary>
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
    [Custom("999-999-9999",
        ErrorMessage = "{0} value does not match the mask {1}.")]
    public string Phone;
}
View Code

调用方式:

    protected void btn_Click(object sender, EventArgs e)
    {
        try
        {
            Customer c = new Customer();
            c.Phone = txt.Text.Trim();
        }
        catch (Exception ex)
        {
        }
    }
View Code

我想实现的是输入的信息与验证信息不符合时,给出错误信息。

_劍客的主页 _劍客 | 初学一级 | 园豆:94
提问于:2014-04-24 10:48
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册