using System.ComponentModel.DataAnnotations.Resources; using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.DataAnnotations { /// /// Validation attribute to indicate that a property field or parameter is required. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "We want users to be able to extend this class")] public class RequiredAttribute : ValidationAttribute { /// /// Default constructor. /// /// This constructor selects a reasonable default error message for public RequiredAttribute() : base(() => DataAnnotationsResources.RequiredAttribute_ValidationError) { } /// /// Gets or sets a flag indicating whether the attribute should allow empty strings. /// public bool AllowEmptyStrings { get; set; } /// /// Override of /// /// The value to test /// false if the is null or an empty string. If /// then false is returned only if is null. #if !SILVERLIGHT public #else internal #endif override bool IsValid(object value) { if (value == null) { return false; } // only check string length if empty strings are not allowed var stringValue = value as string; if (stringValue != null && !AllowEmptyStrings) { return stringValue.Trim().Length != 0; } return true; } } }