Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Having trouble using Date validation #61

Open
stillsilentmind opened this issue Jun 9, 2017 · 5 comments
Open

Having trouble using Date validation #61

stillsilentmind opened this issue Jun 9, 2017 · 5 comments

Comments

@stillsilentmind
Copy link

Surprisingly, most samples do not deal with Date. I have an object that I want to validate the date with. The object I want to supply is:
{ dateTimeGiven: "2001-01-01" } and my struct is:
const newType = t.struct ({ dateTimeGiven: t.Date});

I am getting invalid date for every date that I supply. Can you provide a direct sample of how to validate a date given in a json object? Thanks.

Jim

@gcanti
Copy link
Owner

gcanti commented Jun 9, 2017

"2001-01-01" this is a string, not a (instanceof) Date, therefore the validation fails.

@stillsilentmind
Copy link
Author

stillsilentmind commented Jun 9, 2017 via email

@gcanti
Copy link
Owner

gcanti commented Jun 9, 2017

I mean that tcomb-validation doesn't try to deserialize dates, it just validates them

console.log(t.validate('2001-01-01', t.Date)) // error
console.log(t.validate(new Date(), t.Date)) // ok

You can define a type which validates a string in some format though

const MyDate = t.refinement(t.String, s => s === '2001-01-01') // <= dummy predicate, you can define your own logic here
console.log(t.validate('2001-01-01', MyDate)) // ok

@gcanti
Copy link
Owner

gcanti commented Jun 9, 2017

If you need a library which can deserialize while validating you may want to take a look at https://github.com/gcanti/io-ts. It's the moral successor of tcomb/tcomb-validation (bonus point: compatible with TypeScript)

@stillsilentmind
Copy link
Author

stillsilentmind commented Jun 9, 2017 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants