有条件的或在asp.net mvc2中验证

时间:2011-04-04 19:02:03

标签: asp.net-mvc-2 validation

在我的注册页面中,我有固定电话号码和手机号码字段。

我需要确保用户需要在固定电话或移动电话上添加至少一个电话号码。

我该怎么做?

由于 ARNAB

2 个答案:

答案 0 :(得分:4)

您可以编写自定义验证属性并使用它来装饰您的模型:

[AttributeUsage(AttributeTargets.Class)]
public class AtLeastOnePhoneAttribute: ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = value as SomeViewModel;
        if (model != null)
        {
            return !string.IsNullOrEmpty(model.Phone1) ||
                   !string.IsNullOrEmpty(model.Phone2);
        }
        return false;
    }
}

然后:

[AtLeastOnePhone(ErrorMessage = "Please enter at least one of the two phones")]
public class SomeViewModel
{
    public string Phone1 { get; set; }
    public string Phone2 { get; set; }
}

对于更高级的验证方案,您可以查看FluentValidation.NETFoolproof

答案 1 :(得分:1)

添加可应用于单个属性的解决方案,而不是在类级别覆盖验证方法...

创建以下自定义属性。请注意构造函数中的“otherPropertyName”参数。这将允许您传入其他属性以用于验证。

public class OneOrOtherRequiredAttribute: ValidationAttribute
{
    public string OtherPropertyName { get; set; }
    public OneOrOtherRequiredAttribute(string otherPropertyName)
    {
        OtherPropertyName = otherPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherPropertyName);
        var otherValue = (string)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
        if (string.IsNullOrEmpty(otherValue) && string.IsNullOrEmpty((string)value))
        {
            return new ValidationResult(this.ErrorMessage); //The error message passed into the Attribute's constructor
        }
        return null;
    }
}

然后您可以像这样装饰您的属性:(务必传入要与之比较的其他属性的名称)

[OneOrOtherRequired("GroupNumber", ErrorMessage = "Either Group Number or Customer Number is required")]
public string CustomerNumber { get; set; }

[OneOrOtherRequired("CustomerNumber", ErrorMessage="Either Group Number or Customer Number is required")]
public string GroupNumber { get; set; }