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:
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; }
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"
}