conditional either or validation in asp.net mvc2

2020-03-30 16:26发布

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

2条回答
手持菜刀,她持情操
2楼-- · 2020-03-30 16:52

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; }
查看更多
我只想做你的唯一
3楼-- · 2020-03-30 16:53

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.

查看更多
登录 后发表回答