Either or check required

I want to use ComponentModel DataAnnotations to make sure that at least one of the two properties matters. My model looks like this:

public class FooModel {
   public string Bar1 { get; set; }
   public int Bar2 { get; set; }
}

Basically, I want to check out FooModel so that either Bar1 or Bar2 is required . In other words, you can enter one or the other or both, but you cannot just leave them blank.

I would prefer this to work both on the server side and on an unobtrusive check on the client side.


EDIT: this might be a possible duplicate, as it looks like what I'm looking for

+5
source share
1 answer

ValidationAttribute IsValid IClientValidatable, JavaScript . - .

[AttributeUsage(AttributeTargets.Property)]
    public sealed class AtLeastOneOrTwoParamsHasValue : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var param1 = validationContext.ObjectInstance.GetType().GetProperty("Param1").GetValue(value, null);
            //var param2 = validationContext.ObjectInstance.GetType().GetProperty("Param2").GetValue(value, null);

            //DO Compare logic here.

            if (!string.IsNullOrEmpty(Convert.ToString(param1)))
            {
                return ValidationResult.Success;
            }


            return new ValidationResult("Some Error");
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //Do custom client side validation hook up

            yield return new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "validParam"
            };
        }
    }

:

[AtLeastOneOrTwoParamsHasValue(ErrorMessage="Atleast one param must be specified.")]
+4

All Articles