4

Is it possible to use Data Annotation attribute to manipulate text and return a new one after manipulation?

For example I want to validate a string property for having special characters or multiple spaces between words then return a new string to replace the original property's value.

How possible is that using Data Annotation?

tereško
  • 58,060
  • 25
  • 98
  • 150
Jack Manson
  • 497
  • 1
  • 7
  • 9
  • Can't you just do it inside the get/set part? `Property { get { return _Property.Replace(badChar, goodChar); } }` – Corak Mar 21 '13 at 07:05
  • I think a better approach is a DataBinder: http://stackoverflow.com/a/1734025/7720 – Romias Apr 13 '17 at 20:17

4 Answers4

4

A bit late to answer (2 years!), but yes you can modify the value being validated in a custom DataAnnotations attribute. The key is overriding the IsValid(Object, ValidationContext) method of ValidationAttribute and performing a little reflection magic:

public class MyCustomValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext ctx)
    {
        // get the property
        var prop = ctx.ObjectType.GetProperty(ctx.MemberName);

        // get the current value (assuming it's a string property)
        var oldVal = prop.GetValue(ctx.ObjectInstance) as string;

        // create a new value, perhaps by manipulating the current one
        var newVal = "???";

        // set the new value
        prop.SetValue(ctx.ObjectInstance, newVal);

        return base.IsValid(value, ctx);
    }
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
1

Corak's suggestion is the best way to do it. However, you can write your base class and using reflection you can do whatever you want with the contents of type members.

0

This isn't with a data annotation but just an attribute.

So yes via various methods already discussed here:

How to get and modify a property value through a custom Attribute? Change Attribute's parameter at runtime

It's interesting to note the various solutions from validation to sub classes to 'you can't'

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
0

Here is a package that will probably have what you are expecting: Dado.ComponentModel.Mutations

This example will ensure invalid characters are removed from a string. It doesn't introduce validation, but the System.ComponentModel.Annotations can be used alongside Dado.ComponentModel.Mutations.

public partial class ApplicationUser
{
    [ToLower, RegexReplace(@"[^a-z0-9_]")]
    public virtual string UserName { get; set; }
}

// Then to preform mutation
var user = new ApplicationUser() {
    UserName = "M@X_speed.01!"
}

new MutationContext<ApplicationUser>(user).Mutate();

After the call to Mutate(), user.UserName will be mutated to mx_speed01.

roydukkey
  • 3,149
  • 2
  • 27
  • 43