I’m validating a field in MVC 3 with data annotations:
[StringLength(50, MinimumLength=5)]
public string MyText { get; set; }
Is there a way to provide a dynamic value there? Something like this:
[StringLength(50, MinimumLength=GetMinimumLengthValueFromDb())]
public string MyText { get; set; }
My last resort is to use remote validator. If I won’t find a way to do this with StringLength, I will use RemoteValidator.
No, only compile time values, like constants, can be provided for attributes. This limitation applies to all C# attributes and is not specific to data annotation attributes, but in the case of the
StringLengthAttributeimplies that there is way to provide a different length at runtime.You’ll need to use another kind of validation or maybe create a custom attribute inheriting from
StringLengthAttributethat accepts aTypeand the name of a method on that type as the source for the length value. This approach would be similar to the one used byCustomValidationAttributethat accepts aValidatorTypeand aMethodname as sources for the validation.