conditional either or validation in asp.net mvc2

一笑奈何 提交于 2019-12-04 02:11:24

问题


In my registration page I have land line phone number and mobile number fields.

I need to ensure that the user needs to add at least one phone number either the land line or mobile.

How do I do this?

Thanks Arnab


回答1:


You could write a custom validation attribute and decorate your model with it:

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

and then:

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

For more advanced validation scenarios you may take a look at FluentValidation.NET or Foolproof.




回答2:


Adding a solution that can be applied to individual properties, rather than overriding the validation method at the class level...

Create the following custom attribute. Note the "otherPropertyName" parameter in the constructor. This will allow you to pass in the other property to use in validation.

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;
    }
}

You can then decorate your properties like so: (be sure to pass in the name of the other property to compare with)

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


来源:https://stackoverflow.com/questions/5543012/conditional-either-or-validation-in-asp-net-mvc2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!