Why must a setter be empty, if the property uses annotation attributes?

219 Views Asked by At

i want to use the setter to auto-correct the value and want to use the RequiredAttribute too. But in this case the RequiredAttribute do not work, because the setter is not empty. So, why have the setter to be empty?

    [Required(AllowEmptyStrings = false, ErrorMessage = "The Name cannot be empty. Please correct.")]
    public String Name //{get; set;} <- Required works fine...
    {
        get { return _name; }
        set // <- Required did not work...
        {
            String setValue = Regex.Replace(value, @"^\d+", "");
            setValue = Regex.Replace(setValue, @"[^a-zA-Z0-9_]+", "_");
            _name = setValue;
        }
    }
1

There are 1 best solutions below

2
On BEST ANSWER

Your assumption is actually incorrect. You can use a custom setter with the required attribute.

void Main()
{
    var test = new Test();
    Validator.ValidateObject(test, new ValidationContext(test));    
}

public class Test 
{
    private string _name;
    [Required(AllowEmptyStrings = false, ErrorMessage = "The Name cannot be empty. Please correct.")]
    public String Name
    {
        get { return _name; }
        set 
        {
            String setValue = Regex.Replace(value, @"^\d+", "");
            setValue = Regex.Replace(setValue, @"[^a-zA-Z0-9_]+", "_");
            _name = setValue;
        }
    }
}

This quick and dirty test throws your Required validation message.