jwaliszko / ExpressiveAnnotations

Annotation-based conditional validation library.
MIT License
351 stars 123 forks source link

WebAPI: RequiredIf throws NullReferenceException for properties with DisplayAttribute, where Name does not match property name #118

Closed girtsl closed 8 years ago

girtsl commented 8 years ago

Here is a simplified class to reproduce the bug:

public class SampleModel
{
    [RequiredIf("true", ErrorMessage = "You must enter your first name")]
    [Display(Name = "First name")]
    public string FirstName { get; set; }
}

I traced it to RequiredIfAttribute.IsValidInternal() - validationContext.MemberName contains the display name "First name", which, of course, is not a property name and thus the validationContext.ObjectType.GetProperty() returns null.

Unfortunately I cannot offer a solution as I haven't dealt with MVC validation in depth.

P.S. This was introduced in 2.7.0, commit https://github.com/jwaliszko/ExpressiveAnnotations/commit/b4afd1eef0ef9b4a7d486081812ef8d1d3750b12

jwaliszko commented 8 years ago

Could you please provide some tiny sample for this to be reproduced? I have many properties with names containing spaces used across multiple tests and no error is being thrown.

girtsl commented 8 years ago

My bad for not trying it out in an MVC application - I mostly work with WebApi. You are right, of course, in MVC it works as expected and validationContext.MemberName indeed contains the member's name. I guess it must be a bug in WebAPI's model binder/validator, which puts the DisplayName in MemberName. You can reproduce the issue with the class I posted above and this minimalistic API controller:

public class DefaultController : ApiController
    {
        [HttpPost]
        public IHttpActionResult Index(SampleModel model)
        {
            return Ok();
        }
    }

I see that this is not a bug with your lib, as you are targeting MVC, but it also stops your lib from being used in WebAPI projects. Which, prior to version 2.7.0, worked beautifully.

jwaliszko commented 8 years ago

Thanks for clarification. There were previously issues with this MemberName as well, i.e.

jwaliszko commented 8 years ago

The following commit: https://github.com/jwaliszko/ExpressiveAnnotations/commit/44e2ab792d149abdfe6142a90c0cec84cc4b28a4, will most likely fix both problems mentioned in this topic.

girtsl commented 8 years ago

Yes, it fixes the issue(s). Thanks!