Reputation: 5250
I am mapping the web api Get request complex type input parameter with a model and I want to validate the date format of the input type in the model.
My input uri is as follows http://localhost:xxxx/api/games/?id=5&date=2018-01-17
In my GameController
public IHttpActionResult Get([FromUri]Gamedata) {
if (ModelState.IsValid) {
}
else {
}
}
In my model class
public class Game
{
[Required]
public int? Id { get; set; }
[Required]
public string date { get; set; } // Validate the date format "YYYY-MM-DD"
}
I would like to validate the date format "YYY-MM-DD". How this can be achieved? I am reading this. But don't know which is the annotation to be used?
Upvotes: 1
Views: 7806
Reputation: 1917
You can do this
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
In your model
public class Game
{
[Required]
public int? Id { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime date { get; set; } // Validate the date format "YYYY-MM-DD"
}
You can also look at DateTime.GetDateTimeFormats Method ()
Upvotes: 5