How to Put Conditional Required Attribute into Class Property to Work with Web API

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 neither name or name2 are supplied as long as DocumentType 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



Leave a reply



Submit