akidee / schema.js

Sophisticated JSON schema based data validation and adaptation
MIT License
173 stars 13 forks source link

optional #3

Closed dvv closed 14 years ago

dvv commented 14 years ago

Hi!

{a: ''} fails to validate tolerantly against a: {type: 'number', optional: true}. I'd think a should be just ignored, as it is optional, when a validation fails, no?

--dvv

akidee commented 14 years ago

This depends on the fallback you use. At first, the property a exists ('a' in object === true), and so the value will be validated. And '' is no valid number. You could write a fallback that will remove a value that is optional and not valid. The regular behavior is: If a value exists and is not valid, an error must be pushed. Change the fallback as needed.

dvv commented 14 years ago

I see. You might have guessed that a: '' was due to a how HTML forms work. So effectively a: '' means a: undefined and thus delete obj.a.

Well, could you outline how do I write my own fallback and link it in the fallback chain? I mean, I want to wrap the default castTolerantlyToType()

TIA, --dvv

akidee commented 14 years ago

No, a === '' does not mean a === undefined. In your example, the fallback for "optional: true" is ignored, but the fallback for the violated "type" is called. So you should clone castTolerantlyToType and change the clone to convert '' to 0, or to delete the current property of the parent object. Please take a deeper look and try it for yourself, if you don't want, I will give you an example tomorrow.

Best, Andi

dvv commented 14 years ago

Sure, No, a === '' does not mean a === undefined. I meant I want it be so.

I'll wait since I don't want to copy-paste excellent castTolerantlyToType(). May be we'll find a better way

--dvv

akidee commented 14 years ago

I hope you get it:

http://github.com/akidee/schema.js/commit/d5a5cab60b18748a8bb31345f02ba3ec68301083

With more sophisticated schema.js, I will document the whole API more thoroughly, so that developers can implement their own plugins.

dvv commented 14 years ago

oh, thanks! Will test it tomorrow.