Table of Contents

Class RequiredWhenAttribute

Namespace
OFT.Attributes
Assembly
OFT.Attributes.dll

Behaves like System.ComponentModel.DataAnnotations.RequiredAttribute, but only while the specified source property's value matches one of the provided values; otherwise the property is always considered valid. Derives from System.ComponentModel.DataAnnotations.RequiredAttribute so it is enforced even by validators that run required-only checks (e.g. Validator.TryValidateObject with validateAllProperties: false).

Added in ATAS 8.0.15.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class RequiredWhenAttribute : RequiredAttribute
Inheritance
object
Attribute
ValidationAttribute
RequiredAttribute
RequiredWhenAttribute
Extension Methods

Constructors

RequiredWhenAttribute(string, params object[])

Initializes the attribute.

public RequiredWhenAttribute(string propertyName, params object[] values)

Parameters

propertyName string

Name of the source property whose value controls the required state.

values object[]

Values of the source property for which this property is required.

Properties

PropertyName

Name of the source property whose value determines whether this property is required.

public string PropertyName { get; }

Property Value

string

Values

The set of source property values for which this property is required.

public object[] Values { get; }

Property Value

object[]

Methods

IsValid(object?, ValidationContext)

Validates the value as required when the source property has one of Values; otherwise the value is valid.

protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)

Parameters

value object

The value of the property.

validationContext ValidationContext

The object being validated.

Returns

ValidationResult

The result of the check.

Exceptions

InvalidOperationException

The object has no property named PropertyName.