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

I am checking a field in MVC 3 with data annotations:

[StringLength(50, MinimumLength=5)] public string MyText { get; set; } 

Is there a way to provide dynamic value there? Something like that:

 [StringLength(50, MinimumLength=GetMinimumLengthValueFromDb())] public string MyText { get; set; } 

My last resort is to use a remote validator. If I do not find a way to do this with StringLength , I will use RemoteValidator .

+6
source share
1 answer

No, only compile-time values, such as constants, can be provided for attributes. This restriction applies to all C # attributes and is not specific to data annotation attributes, but in the case of StringLengthAttribute , it is understood that there is a way to provide different lengths at runtime.

You will need to use another type of validation or create your own attribute that inherits from StringLengthAttribute , which takes Type and the method name for this type as the source for the length value. This approach will be similar to the one used by CustomValidationAttribute , which takes the names ValidatorType and Method as sources for verification.

+7
source

Source: https://habr.com/ru/post/902297/


All Articles