1

I am trying to attach an attribute to the particular property in the this case the FirstName but the problem is in this code it is attaching to the birthday datetime property as well . what might be the problem with this

 public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        if ( metadata.PropertyName == "FirstName")
            attributes = new List<Attribute>() { new RequiredAttribute() };

        return base.GetValidators(metadata, context, attributes);
    }
}

public class User
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
}



 protected void Application_Start()
    {

        //ModelValidatorProviders.Providers.Clear();
        //ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider()); 
        ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());
        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
    }

can someone can explain how GetValidators is working?

2
  • Is this a simplified example? adding validators in this way is a bit unusual. Commented Apr 8, 2012 at 7:06
  • just playing around for larger stuff Commented Apr 8, 2012 at 7:19

1 Answer 1

3

Your problem has nothing to do with your GetValidators method.

Value types like (int, decimal, DateTime, etc.) are required by default. Because otherwise the model binder cannot set their values if they are not sent with the request.

So you need to change your Birtday property to nullable if you don't want to be required:

public class User
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? Birthday { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.