1

What is a good practise to validate a JavaScript Object which contains date fields?

There are JSON validators like tv4 which can validate the format of strings.

However, our business logic works with dates of instance JavaScript-Date, and these objects won't validate.

Our current procedure is

  1. Read business object with JSON.parse() using a date reviver
  2. Process the object with business logic, then validate with
  3. Convert the object to JSON with a date stringifier
  4. Read string back with JSON.parse(), now without reviver
  5. Validate this object

Is there a better way to validate opposed to steps 3, 4 and 5? Preferably validating the business object directly?

Example:

The JSON string

{
    "birth": "1994-03-17"
}

Schema for the JSON string

{
    type: 'string',
    format: 'date-time'
}

The business object

{
    birth: new Date("1994-03-17")
}
Community
  • 1
  • 1
Wolfgang Kuehn
  • 12,206
  • 2
  • 33
  • 46

1 Answers1

2

If you are using the tv4 library you can do:

tv4.addFormat('date-time', function (data) {
    if (data instaceof Date) return null;
    else return "not a valid date";
});

and your validation should be:

{
    type: "object",
    format: "date-time"
}

This method is mentioned in the question you posted (json schema date-time does not check correctly)

Community
  • 1
  • 1
Tsanyo Tsanev
  • 1,269
  • 10
  • 11