gcanti / tcomb-validation

Validation library based on type combinators
MIT License
400 stars 23 forks source link

Having trouble using Date validation #61

Open stillsilentmind opened 7 years ago

stillsilentmind commented 7 years ago

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 commented 7 years ago

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

stillsilentmind commented 7 years ago

Would you be able to provide a simple example of a date being supplied and validated? i am fairly new to using your lib, but like it. just cant seem to get over the date hump. :)

Any help would be appreciated.

On Thu, Jun 8, 2017 at 10:15 PM, Giulio Canti notifications@github.com wrote:

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

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/gcanti/tcomb-validation/issues/61#issuecomment-307297294, or mute the thread https://github.com/notifications/unsubscribe-auth/Ab8N67pNiFdWszkNwLQjstmquG6pG_pQks5sCNTUgaJpZM4N06It .

gcanti commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

Thank you for both comments. I didn't quite understand but I do now.

On Jun 8, 2017 11:00 PM, "Giulio Canti" notifications@github.com wrote:

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)

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/gcanti/tcomb-validation/issues/61#issuecomment-307302821, or mute the thread https://github.com/notifications/unsubscribe-auth/Ab8N6-ZZp7MAy_G5X8IoII9HJJxKiBOaks5sCN9xgaJpZM4N06It .