Forked from FWest98/ConditionalValidationAttribute.cs
Created
September 5, 2021 14:44
-
-
Save chinhvo/625ccaa02287a383840768500c7afe5d to your computer and use it in GitHub Desktop.
.NET Core 3 Conditional Model Validation Attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; | |
namespace Foo { | |
// Implementation makes use of the IPropertyValidationFilter interface that allows | |
// control over whether the attribute (and its children, if relevant) need to be | |
// validated. | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] | |
public class ConditionalValidationAttribute : Attribute, IPropertyValidationFilter { | |
public string OtherProperty { get; set; } | |
public object OtherValue { get; set; } | |
public ConditionalValidationAttribute(string otherProperty, object otherValue) { | |
OtherProperty = otherProperty; | |
OtherValue = otherValue; | |
} | |
public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEntry) { | |
// Default behaviour if no other property is set: continue validation | |
if (string.IsNullOrWhiteSpace(OtherProperty)) return true; | |
// Get the property specified by the name. Might not properly work with | |
// nested properties. | |
var prop = parentEntry.Metadata.Properties[OtherProperty]?.PropertyGetter?.Invoke(parentEntry.Model); | |
return prop == OtherValue; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
namespace Foo { | |
public class Model { | |
public bool ShouldCheckOther { get; set; } | |
[Required] | |
[ConditionalValidation(nameof(ShouldCheckOther), true)] | |
public string DependentRequired { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment