0

So I have a simple custom validation attribute:

public class MyCustomValidator : CustomValidationAttribute
{
    public bool IsLive { get; set; }

    public MyCustomValidator()
    {
        //Service locator stuff
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return ValidationResult.Success;
    }
}

MyCustomValidor inherits the class below as all my custom validators need access to this.

public abstract class CustomValidationAttribute : ValidationAttribute
{
    public Type MessageResource { get; set; }

    public string MessagePrefix { get; set; }
}

Then I call this in my viewModel which looks a little like this:

public class MyViewModel
{
    private static bool IsWebLive;

    [MyCustomValidator(IsWebLive = IsWebLive, MessageResource = typeof(MyResourceFile), MessagePrefix = "ErrorMessage")]
    public string SampleValue { get; set; }
}

Where I am passing the private IsWebLive into the validator I am getting an error saying an attribute argument must be a constant expression, typeof expression or array. I know I'm probably doing this wrong. But how can I pass this bool into the Validator as I don't have access to what is setting it anywhere else in my system;

I also cannot privately set IsLive/MessageResource/MessagePrefix in the MyCustomValidator as my custom validator stuff is generic and MessagePrefix and MessageResource are accessible in all my custom validators.

Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
Ben
  • 187
  • 3
  • 12

2 Answers2

1

Sorry but this is not possible. Constructor parameters for attributes must be known at compile time because they are intended as metadata on the type or method NOT something that would be used per call or instance.

dknaack
  • 60,192
  • 27
  • 155
  • 202
  • Ok thanks, I thought it could be something like that, but thought I'd ask anyway. – Ben Aug 04 '14 at 11:29
0

What you could have done is simple use the CustomValidationAttribute providing it a static method to do your validation. When calling your static method one of the parameters you provide would be the validation context which will contain all the properties in your view model under the ObjectInstance property. So for example you would simple have IsWebLive available for you to do a conditional tests in your static method. No need to inherit and no need for the IsLive property.

Kirby
  • 1,739
  • 1
  • 17
  • 21