How to get and modify a property value through a custom Attribute?

后端 未结 4 1601
遇见更好的自我
遇见更好的自我 2020-12-06 10:18

I want to create a custom attribute that can be used on a property like:

[TrimInputString]
public string FirstName { get; set; }

that will

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 10:23

    iam doing this , not very convincing way but its working

    demo class

    public class User
    {
    
    [TitleCase]
    public string FirstName { get; set; }
    
    [TitleCase]
    public string LastName { get; set; }
    
    [UpperCase]
    public string Salutation { get; set; }
    
    [LowerCase]
    public string Email { get; set; }
    
    }
    

    Writing Attribute for LowerCase, others can be written in the similar manner

    public class LowerCaseAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
           //try to modify text
                try
                {
                    validationContext
                    .ObjectType
                    .GetProperty(validationContext.MemberName)
                    .SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
                }
                catch (System.Exception)
                {                                    
                }
    
            //return null to make sure this attribute never say iam invalid
            return null;
        }
    }
    

    Not very elegant way as its actually implementing Validation attribute but it works

提交回复
热议问题