0

I am working on an API and part of the JSON input are some dates. The format that I need to get and store is the ISO8601 format (e.g. 2017-09-25T05:35:59 +00:00) and, according to W3 the string format should be YYYY-MM-DDThh:mm:ssTZD. Now, I am having trouble verifying the string format. I have tried two separate things:

  1. Use data annotations

    [Required]
    [RegularExpression("YYYY-MM-DDThh:mm:ssTZD", ErrorMessage = "The date time provided does not match the ISO8601 standard YYYY-MM-DDThh:mm:ssTZD")]
    public DateTimeOffset StartValidation { get; set; }
    
  2. Create my own validation

    public class DateTimeFormatValidation: ValidationAttribute{
    
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //check if the object is null or empty
       if (value ==null)
            return new ValidationResult("The date time cannot be null");
    
        DateTimeOffset dateTime = value as DateTimeOffset? ?? new DateTimeOffset();
    
      if (!DateTimeOffset.TryParseExact(value.ToString(), "YYYY-MM-DDThh:mm:ssTZD",
    CultureInfo.CurrentCulture, DateTimeStyles.AllowInnerWhite, out dateTime))
           return new ValidationResult("Wrong date time format" + value);
    
      return null;
    
    }}
    

In the first case, it just returns the string saying that the format is not valid. In the second case, I get the following error

    Wrong date time format 9/25/2017 5:35:59 AM +00:00

I also looked into the DateTimeStyles and maybe changing the separator but I'm not sure that's the case.

JSON input:

    "period": {
        "startHistory": "2017-09-25T05:35:59+00:00",
        "startValidation": "2017-09-25T05:35:59+00:00",
        "endValidation": "2017-09-25T05:35:59:+00:00"
    }
MonicaS
  • 155
  • 1
  • 3
  • 18
  • Possible duplicate of [How to parse and generate DateTime objects in ISO 8601 format](https://stackoverflow.com/questions/36313998/how-to-parse-and-generate-datetime-objects-in-iso-8601-format) Maybe [ISO8601 formatted string to DateTime](https://stackoverflow.com/questions/36267183/iso8601-formatted-string-to-datetime) can also help? – rmjoia Oct 03 '17 at 12:47
  • The first obviously doesn't work because that is not a valid regular expression to test as you want (ie RegEx doesn't understand that when you say yyyy you mean a numerical year). The second method is a bit weird because you have already parsed the json into a `DateTimeOffset` before you are calling this validator. So all you are testing is whether when you called `ToString` you created a string in the right format. That string you create with `value.ToString()` has nothing to do with the value in your json... – Chris Oct 03 '17 at 12:52
  • @rmjoia: the problem is that the validation seems to be happening at the wrong time more than anything else so don't think its a duplicate as it stands. – Chris Oct 03 '17 at 12:53
  • @Chris ok then. Thanks – rmjoia Oct 03 '17 at 12:57
  • @rmjoia just checked that article. It's not a duplicate indeed. I do agree that the validation is happening at the wrong time but how can I check the JSON input then before being put in the DateTimeOffset? – MonicaS Oct 03 '17 at 12:57
  • @MonicaS can you deserialize it? – rmjoia Oct 03 '17 at 12:58
  • @rmjoia sure but I was thinking that there could be a validation before serializing? Or maybe I'm wrong? – MonicaS Oct 03 '17 at 13:02
  • well, I'm not sure, would have to try.. but the deserialization might already validate that, write a simple unit test using for instance, JSON.NET and give it a try – rmjoia Oct 03 '17 at 13:03
  • How are you deserializing it? Answers like https://stackoverflow.com/questions/21256132/deserializing-dates-with-dd-mm-yyyy-format-using-json-net/37441177#37441177 might be of help to you (that talks about how to specify a specific date format in the converter). – Chris Oct 03 '17 at 13:04
  • @rmjoia Working on that now. Will keep you updated. Thanks – MonicaS Oct 03 '17 at 13:05
  • @Chris `public IHttpActionResult Check([FromBody]Schedule schedule) { //todo if (schedule == null) return BadRequest(); if (ModelState.IsValid) return new CheckResult("No rule has been violated", Request); return new CheckResult("Invalid model state \n",Request, ModelState); }` – MonicaS Oct 03 '17 at 13:20

0 Answers0