Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to provide a runtime value to StringLength validator in MVC 3?

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.

like image 950
valerii.sverdlik Avatar asked Nov 24 '11 11:11

valerii.sverdlik


1 Answers

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.

like image 132
João Angelo Avatar answered Sep 28 '22 06:09

João Angelo