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 StringLengthAttribute
implies 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 StringLengthAttribute
that accepts a Type
and the name of a method on that type as the source for the length value. This approach would be similar to the one used by CustomValidationAttribute
that accepts a ValidatorType
and a Method
name as sources for the validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With