2

这是我的模型:

[RegularExpression(@"^08[589][0-9]{8}$", ErrorMessage = "Invalid Number!")]
public string Phone { get; set; }

[ForeignKey]
public long PhoneType { get; set; } // 1-CellPhone , 2-Phone

因此,如果我想说更具体的话,我想RegularExpression通过更改来更改验证:PhoneType

如果用户CellPhoneDropDownList验证中选择

[RegularExpression(@"^08[589][0-9]{8}$", ErrorMessage = "Invalid Number!")] 

如果选择Phone验证是

 [RegularExpression("^[1-9][0-9]{9}$", ErrorMessage = "Invalid Number!")]

你的建议是什么?

4

1 回答 1

6

您可以编写自定义验证属性:

public class PhoneAttribute : ValidationAttribute
{
    private readonly string _phoneTypeProperty;
    public PhoneAttribute(string phoneTyperoperty)
    {
        _phoneTypeProperty = phoneTyperoperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_phoneTypeProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format("Unknown property: {0}", _phoneTypeProperty));
        }

        var phone = Convert.ToString(value, CultureInfo.CurrentCulture);
        if (string.IsNullOrEmpty(phone))
        {
            return null;
        }

        var phoneType = (long)property.GetValue(validationContext.ObjectInstance, null);
        Regex regex = null;
        if (phoneType == 1)
        {
            regex = new Regex(@"^08[589][0-9]{8}$");
        }
        else if (phoneType == 2)
        {
            regex = new Regex("^[1-9][0-9]{9}$");
        }
        else
        {
            return new ValidationResult(string.Format("Unknown phone type: {0}", phoneType));
        }

        var match = regex.Match(phone);
        if (match.Success && match.Index == 0 && match.Length == phone.Length)
        {
            return null;
        }

        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }
}

然后用这个属性装饰你的视图模型属性:

public class MyViewModel
{
    [Phone("PhoneType", ErrorMessage = "Invalid Number!")]
    public string Phone { get; set; }

    public long PhoneType { get; set; }
}

如果您想通过验证让您的生活更轻松,另一种可能性(我强烈推荐)是使用FluentValidation.NET。看看定义验证规则是多么容易,而不是编写大量的管道代码,并且不再能够理解哪个部分是管道,哪个部分是实际验证。使用 FluentValidation.NET 没有管道。您以流利的方式表达您的验证要求:

public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
    public MyViewModelValidator()
    {
        RuleFor(x => x.Phone)
            .Matches(@"^08[589][0-9]{8}$").When(x => x.PhoneType == 1)
            .Matches("^[1-9][0-9]{9}$").When(x => x.PhoneType == 2);
    }
}

只需将此验证器与前一个进行比较。

于 2012-05-07T11:24:34.017 回答