Home > Mobile >  Custom Validation Attribute for model C#
Custom Validation Attribute for model C#

Time:04-08

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

CodePudding user response:

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
}

CodePudding user response:

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();
}
  • Related