Home > OS >  Asp.net core webapi input format validation
Asp.net core webapi input format validation

Time:04-13

I am working on web API (Asp.net core) I have a get method that takes (start and end date as input parameter)

I would like to make sure the date is in "YYYY-MM-DD" formats. otherwise, error "Date should be in YYYY-MM-DD format"

I am using fluent validation but not sure how to validate it. or via data annotation

public async Task<IActionResult> Get([FromQuery] DataParameter input){

}

public class DataParameter {
 public DateTime? StartDate{get;set;}
public DateTime? EndDate{get;set;}
}

Please advice

CodePudding user response:

You can use string and RegularExpression

public class DataParameter
{
   [RegularExpression(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$", ErrorMessage = "Date should be in YYYY-MM-DD format")]
   public string StartDate { get; set; }

   [RegularExpression(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$", ErrorMessage = "Date should be in YYYY-MM-DD format")]
   public string EndDate { get; set; }
}

The regex is from here

Or create your own attribute, something like this

public class DateFormatAttribute : ValidationAttribute
{
    private readonly string _format;

    public DateFormatAttribute(string format)
        : base($"Date should be in {format} format.")
    {
        _format = format;
    }

    public override bool IsValid(object value)
    {
        if (value is not string dateStr)
        {
            return false;
        }

        return DateTime.TryParseExact(dateStr, _format, CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
    }
}

Then use it as follows

[DateFormat("yyyy-MM-dd")]
public string StartDate { get; set; }

FluentValidation implementation

RuleFor(c => c.StartDate)
   .Must(x => DateTime.TryParseExact(x, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
   .When(x => !string.IsNullOrWhiteSpace(x.StartDate))
   .WithMessage("Date should be in yyyy-MM-dd format");

Note that StartDate and EndDate are strings

  • Related