How to put conditional Required Attribute into class property to work with WEB API?
You can implement your own ValidationAttribute
. Perhaps something like this:
public class RequireWhenCategoryAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var employee = (EmployeeModel) validationContext.ObjectInstance;
if (employee.CategoryId == 1)
return ValidationResult.Success;
var emailStr = value as string;
return string.IsNullOrWhiteSpace(emailStr)
? new ValidationResult("Value is required.")
: ValidationResult.Success;
}
}
public sealed class EmployeeModel
{
[Required]
public int CategoryId { get; set; }
[RequireWhenCategory]
public string Email { get; set; } // If CategoryId == 1 then it is required
}
This is just a sample. It may have casting issues, and I'm not sure this is the best approach to solve this problem.
c# conditional Required Attribute
Try this?
public partial class Zone
{
[RequireCondition(1)]
public int LastCount { get; set; }
}
public class RequireConditionAttribute : ValidationAttribute
{
private int _comparisonValue;
public RequireCondition(int comparisonValue)
{
_comparisonValue = comparisonValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is int && (int)value < comparisonValue)
{
return new ValidationResult($"{validationContext.DisplayName} value must be greater than one.");
}
return ValidationResult.Success;
}
}
Conditionally required property using data annotations
Out of the box I think this is still not possible.
But I found this promising article about Mvc.ValidationToolkit (also here, unfortunately this is only alpha, but you probably could also just extract the method(s) you need from this code and integrate it on your own), it contains the nice sounding attribute RequiredIf
which seems to match exactly your cause:
- you download the project from the linked zip and build it
- get the built dll from your build folder and reference it in the project you are using
- unfortunately this seems to require reference to MVC, too (easiest way to have that is starting an MVC-Project in VS or
install-package Microsoft.AspNet.Mvc
) - in the files where you want to use it, you add
using Mvc.ValidationToolkit;
- then you are able to write things like
[RequiredIf("DocumentType", 2)]
or[RequiredIf("DocumentType", 1)]
, so objects are valid if neithername
orname2
are supplied as long asDocumentType
is not equal to 1 or 2
Conditional validation in MVC.NET Core (RequiredIf)
Found an answer
Changed
if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
to
if (proprtyvalue.ToString() == DesiredValue.ToString() && value.ToString() == "N/A")
ASP.NET Core Conditional Validation for controls
You need to implement IValidatableObject
. Put validation checks in Validate
method. return list of errors in the end.
public class PageViewModel : IValidatableObject
{
public bool? HasControl { get; set; }
public bool? Critical { get; set; }
public string Description { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> errors = new List<ValidationResult>();
if (HasControl == true)
{
if (Critical == null)
errors.Add(new ValidationResult($"{nameof(Critical)} is Required.", new List<string> { nameof(Critical) }));
if (string.IsNullOrWhiteSpace(Description))
errors.Add(new ValidationResult($"{nameof(Description)} is Required.", new List<string> { nameof(Description) }));
}
return errors;
}
}
Related Topics
System.Io.File.Create Locking a File
Easiest Way to Parse "Querystring" Formatted Data
How to Retrieve a List of Parameters from a Stored Procedure in SQL Server
Task.Factory.Startnew with Async Lambda and Task.Waitall
How to Add an Item to a Listbox in C# and Winforms
Service Starting a Process Wont Show Gui C#
File Write Permission Issue Under "Program Files" Folder
ASP.NET Core 2.0 Disable Automatic Challenge
Entity Framework Ef.Functions.Like VS String.Contains
Stack Overflow Exception in C# Setter
Why Do I Get "System.Data.Datarowview" Instead of Real Values in My Winforms Listbox
Circular Reference Causing Stack Overflow with Automapper
How to Convert String "07:35" (Hh:Mm) to Timespan
Conditional Datagridview Formatting
Show Yes/No Instead True/False in Datagridview