Setting the maximum length in a StringLengthAttribute element in code

I am working on some code that uses DataAnnotation attributes in viewmodels, and overrides some attributes programmatically under certain circumstances.

Changing ErrorMessage to various ValidationAttributes types, no problem.

Changing DataFormatString to DisplayFormatAttributes without problems.

Changing MinimumLength to StringLengthAttribute , no problem. But .. MaximumLength does not have a public setter !?

Is there a reason why this one property stands out as a personal setter when everything around it is publicly available? Is there a workaround that I can use to programmatically change the maximum length of a StringLengthAttribute ?

+4
source share
3 answers

Since the only way to set the MaximumLength property is through the attribute constructor, there is no programmatic way to change it after building. You can always use personal reflection to do what you need, provided that you use the code with sufficient trust. If you do not want (or cannot) go along this route, another option would be to replace the viewing models in these conditions, and not just update the attributes as necessary. Then you can simply create the required attribute for each individual view model and not worry about changing the attribute itself programmatically.

One recent option is to write your own StringLength attribute. You can pretty easliy mimic the functionality of the embedded version, since its IsValid() method is very simple:

 public override bool IsValid(object value) { int num = (value == null) ? 0 : ((string)value).Length; return value == null || (num >= this.MinimumLength && num <= this.MaximumLength); } 

Guiding this, but including the public installer in the MaximumLength property MaximumLength should get what you need.

+3
source

Assuming you are using your own ModelMetadataValidatorProvider, as I outlined in How to add a validation attribute for a model property in TemplateEditor in MVC3 , in your overriding of the GetValidators method, you can iterate through the validators returned by the base method, delete the current StringLengthAttribute and replace your StringLengthAttribute with the desired value of MaxLength.

+1
source

Since this code is viewmodel specific, your ViewModel implements the IValidateableObject interface and validates it there.

 public IEnumerable Validate(ValidationContext validationContext) { if (YourField.Length == 2) { yield return new ValidationResult("ut oh!!"); } }
public IEnumerable Validate(ValidationContext validationContext) { if (YourField.Length == 2) { yield return new ValidationResult("ut oh!!"); } } 
0
source

All Articles