简体   繁体   中英

What does [Required] do?

I found nothing on the web what [Required] actually does. The msdn-article is not explorative at all.

static class Program
{
    public static Main()
    {
        var vustomer = new CustomerClass();
    }
}

public class CustomerClass
{
    public string m_FirstName;
    [Required]
    public string m_LastName;
}

As far as i understand, that should throw an exception since m_LastName is required, but not set. But i don't get one. I don't get what it's good for and what this actually does.

RequiredAttribute , like all other attributes, does nothing by itself other than annotate something (in this case, a field of a type). It is entirely up to the application that consumes the type to detect the presence of the attribute and respond accordingly.

Your sample program does not do this, so the attribute does not have any visible effect. Certain frameworks such as ASP.NET MVC and WPF do check for and respond to the presence of the attribute.

This attribute is used by the Validator class to add validation errors based on any types that inherit from ValidationAttribute . This is used by MVC model validation , for example.

Documentation on RequiredAttribute :

Specifies that a data field value is required.

However this validation is typically only performed in the UI layer. It is not "baked" into the constructor or other low-level usage. If you want to manually fire the validation you could do something like:

var customer = new CustomerClass();
var context = new ValidationContext(customer, serviceProvider: null, items: null);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(customer, context, results);

if (!isValid)
{
    foreach (var validationResult in results)
    {
        Console.WriteLine(validationResult.ErrorMessage);
    }
}

To add to the current answers, these are some of the practical uses I can think of out of my head:

  • Entity Framework use this to model the database as not nullable fields.
  • Javascript client side validation provides javascript libraries for checking if the input field has any data, else prevent the form submission avoiding unnecesary roundtrips to the server.
  • Server side validation (when doing model binding) also check when you are posting a model with that decorator that the attribute passed in is in the request. This determines if the model state should be set to an invalid state or not. (1)
  • There are also annotation for JSON.NET library that changes how the model is serialized/unserialized. I'm pretty confident (but not sure) that the Validate Schema of Json.net does take into consideration the 'Required' attribute when validating a schema.
  • Other attribute decorators are used on web services, but 'Required' is not one I know has it uses in this scenario.
  • Web api uses this attribute to mark the property as required on documentation help pages and model binding.
  • You can create your own application logic that can be aware of the 'Required' property. For example, on a view to mark the property with an * in the label if it's required.

This are some uses but you are not limited to them.

(1) Note: if your property is, for example, an int and you decorate it with Required, model state will never be on a invalid state. You should use Nullable properties for this use-cases.

In C#, attributes are almost decoration to classes and properties.

Except for a few security related attributes, most do nothing. They are used by a higher-level framework to do something.

In the case of ASP.NET 4 MVC, only when the object is part of a request that attribute is used to generate an error.

If you want to use that attribute in any other environment, you must write code to inspect it.

It won't do anything from a plain old public static void Main()

Specifies that a data field value is required.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx

There are several attribute properties that can manipulate how this attribute is applied.

There's a MSDN article that talks about how to use validation attributes to annotate your object models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM