'Custom Validation Attribute for model C#
I have a model
public class SendEmail
{
public bool IsScheduled { get; set; }
public DateTime ScheduleDate { get; set; }
public List<ScheduleAttachement> ScheduleAttachement {get; set;}
}
public class ScheduleAttachement
{
public string Name { get; set; }
public string Attachement { get; set; }
}
I want to do a custom validation to check if bool IsScheduled == true, ScheduleAttachement must contain a value. If not throw 400 bad request
Solution 1:[1]
if (SendEmail.IsScheduled)
{
//true, in here you can check for a value:
if(SendEmail.ScheduleAttachement == null || (!SendEmail.ScheduleAttachement.Any()))
{
//list is null or empty, throw error
}
}
less code list null or empty check:
if (list?.Any() != true)
{
//list is null or empty, throw error
}
Solution 2:[2]
In your controller layer
var emailToCheck = new SendEmail();
if (!emailToCheck.IsScheduled && emailToCheck.ScheduleAttachement.Count() == 0)
{
return BadRequest();
}
If you want to add a custom message lookup this answer.
Edit
if (!emailToCheck.IsScheduled && emailToCheck.ScheduleAttachement?.Where(x => x.Attachment != null && x.Name != null).Count() > 0)
{
return BadRequest();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
