0

我正在尝试验证电话号码。所以我声明了一些这样的数据注释:

    [IsCellAcceptable(ErrorMessageResourceName = "IsCellAcceptable", ErrorMessageResourceType = typeof(Resources.PageResources))]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "UserCell", ResourceType = typeof(Resources.PageResources))]
    public String Cell { get; set; }

如果 Cell 等于 0 999 999 99 99,我想将其返回为有效并且我想像这样保存它:09999999999。但 IsValid 函数只能验证它,不能操作它。

public class IsCellAcceptableAttribute : ValidationAttribute
{
    public IsCellAcceptableAttribute()
        : base()
    {

    }

    public override bool IsValid(object value)
    {
        if (value == null)
            return true;
        if (value == "")
            return true;

        string phoneOutput = string.Empty;
        string phoneInput = Convert.ToString(value);
        phoneInput = phoneInput.Replace(" ", "");

        foreach (char ch in phoneInput)
        {
            if (Char.IsNumber(ch))
            {
                phoneOutput += ch;
            }
            else
            {
                return false;
            }
        }

        if (phoneOutput.Length <= 14 && phoneOutput.Length >= 10)
        {
            return true;
        }

        return false;
    }

所以我的问题是在验证对象时如何操作对象?

4

1 回答 1

2

你为什么不事后操纵价值?

if (IsValid(value)) 
{
        // Manipulate here
        phoneNumber = phoneNumber.Replace(" ", "");
}

else
{
        // Not valid
}
于 2012-11-19T01:15:05.157 回答