2

Can anyone explain why it is assumed that a non nullable type property should always have a RequiredAttribue?

I am trying to write a label helper that will auto append * or change the css class so that I can indicate to the user that the field is required. However when querying the metadata the non nullable properties end up with a required attribute.

MVC Source Code:

protected override IEnumerable<ModelValidator> GetValidators(
    ModelMetadata metadata, ControllerContext context,
    IEnumerable<Attribute> attributes)
{
    _adaptersLock.EnterReadLock();

    try
    {
        List<ModelValidator> results = new List<ModelValidator>();

        if (metadata.IsRequired &&
            !attributes.Any(a => a is RequiredAttribute))
        {
            //******* Why Do this? 
            attributes = attributes.Concat(new[] { new RequiredAttribute() });
        }

        foreach (ValidationAttribute attribute in
            attributes.OfType<ValidationAttribute>())
        {
            DataAnnotationsModelValidationFactory factory;

            if (!_adapters.TryGetValue(attribute.GetType(), out factory))
                factory = _defaultFactory;

            results.Add(factory(metadata, context, attribute));
        }

        return results;
    }
    finally
    {
        _adaptersLock.ExitReadLock();
    }
}

1 Answer 1

2

Personally, I think it's because the designers of the framework have missed the point with nullable data!

It would appear that they have assumed that if a field isn't nullable, it must be required.

Unfortunately, as you're presumably discovering, this isn't always the case.

The most common instance of this I can think of is a text field which is provided by a user that could be blank, but you want to keep it as NULL until the user has provided a value. In this case you get three valid cases: 'Not Set' (NULL), 'Empty' (not NULL) or an actual value.

So - to answer your question, no - I can't explain it. Perhaps it's a mistake?

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. It makes the 'required' property very confusing and unusable. I since found Jeremy Skinner having the same issues with it. jeremyskinner.co.uk/2010/01/13/…

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.