1

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?

1
  • 2
    Why don't you use DateTime object instead for string? then you can format the dateString based on locale na? Commented Jan 17, 2018 at 11:52

1 Answer 1

5

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 ()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.